Re:Python Best Practice Patterns
by unoti on Friday February 28, 2014 @11:45AM
(#7319842)
I never knew you could use __enter__ and __exit__ to code your own things that work with the 'with' statement. Well worth the read!
[ Parent
| on HN ]
For simple context managers, an easier method is to use contextlib.contextmanager (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>
"""You 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()You 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.