3 ms·
I never knew you could use __enter__ and __exit__ to code your own things that work with the 'with' statement. Well worth the read!
by unoti 13y ago
I never knew you could use __enter__ and __exit__ to code your own things that work with the 'with' statement. Well worth the read!
- ajtulloch 13y agoFor simple context managers, an easier method is to use contextlib.contextmanager (http://docs.python.org/library/contextlib.html http://docs.python.org/library/contextlib.html). from contextlib import contextmanager @contextmanager def tag(name): print "<%s>" % name yield print "</%s>" % name with tag("h1"): print "foo" """ <h1> foo </h1> """
- masklinn 13y agoYou don't even have to create a full object if there's no need to: @contextlib.contextmanager def manager(*args): object = initialize(args) try: yield object finally: # cleanup object.close()
- gmjosack 13y agoYou might be interested in the docs on the Data Model [0] to learn more about the various "dunder" (__foo__) methods. There are a ton of cool things you can do with python objects. [0] http://docs.python.org/2/reference/datamodel.html http://docs.python.org/2/reference/datamodel.html