Hacker News new | ask | show | jobs
by unoti 4490 days 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!
3 comments

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.

[0] http://docs.python.org/2/reference/datamodel.html