Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What things to be aware of when using the with-statement for own classes?

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?

like image 440
moooeeeep Avatar asked Jan 18 '12 10:01

moooeeeep


1 Answers

(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.

like image 167
Marcin Avatar answered Oct 13 '22 01:10

Marcin