I am planning to implement C++-like constructor/destructor functionality to one of my Python classes using the handy with statement. I've come accross this statement only for file IO up to now, but I thought it would be rather helpful for connection-based communication tasks as well, say sockets or database connections. Things that eventually need to be closed.
In PEP 343 (linked above) it is said, that with
needs the methods __enter__
and __exit__
, and my straight-forward implementation of this appears to work as intended.
class MyConnection:
def __init__(self):
pass
def __enter__(self):
print "constructor"
# TODO: open connections and stuff
# make the connection available in the with-block
return self
def __exit__(self, *args):
print "destructor"
# TODO: close connections and stuff
with MyConnection() as c:
# TODO: do something with c
pass
Which yields the output (as expected):
constructor
destructor
Should it really be this easy? What are the things to consider besides this? Why do so many libraries (apparantly) lack this functionality yet? Have I missed something?
(a) It's that easy
(b) An alternative approach is a decorator function, which decorates functions (and classes, but not for this use-case), and also allows code to be called both before and after the wrapped function. Those seem slightly more common.
(c) I don't think you're missing anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With