News for hackers. Stuff that matters.
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!
Re:Python Best Practice Patterns by ajtulloch on Friday February 28, 2014 @12:02PM (#7319950)
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>
  """
Re:Python Best Practice Patterns by masklinn on Friday February 28, 2014 @12:04PM (#7319969)
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()
Re:Python Best Practice Patterns by gmjosack on Friday February 28, 2014 @12:22PM (#7320097)
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