[Python-Dev] PEP 310 - A standard way to wrap objects?

Nick Coghlan ncoghlan at email.com
Wed Jun 16 13:42:03 EDT 2004

After the recent discussion of resource acquisition, I went back and read PEP 
310 again myself.

Something that I wondered was whether it would be possible to include in the 
PEP a generic wrapper function that could be used inline in the 'with' 

That is, instead of resource control via lots of throwaway subclasses like this:

  class Resource_Foo(Foo):
    __exit__ = foo_done

  with myFoo = Resource_Foo(args):
    # Do stuff

We would have:

  with myFoo = resource(Foo(args), Foo.foo_done):
    # Do stuff


  with myFile = resource(file("bar.txt"), file.close):
    # Do stuff

  my_bar = Bar()
  with resource(my_bar, my_bar.start, my_bar.stop):
    # Do stuff

Having a recommended way to wrap objects which don't support the 'with' 
protocol natively would seem to be better than having everyone invent there own 

Possible definition for the 'resource' function (this mechanism for adding the 
relevant methods has been tested in Python 2.2):

  def resource(obj, get_resource=None, free_resource):
    # Set up the enter method (if there is one)
    if get_resource:
      enter_obj = getattr(enter_meth, "im_self", None)
      if not enter_obj:
        # It's a function or unbound method
        obj.__enter__ = lambda: get_resource(obj)
      elif enter_obj is obj:
        # It's a bound method of our object
        obj.__enter__ = get_resource
        raise ValueError("Resource and bound enter method do not match")

    # Set up the exit method
    if not getattr(free_resource, "im_self", None):
      # It's a function or unbound method
      obj.__exit__ = lambda: free_resource(obj)
    elif free_resource.im_self is obj:
      # It's a bound method of our object
      obj.__exit__ = free_resource
      raise ValueError("Resource and bound exit method do not match")

    # Return the object so that we can use the assignment
    # form of the 'with' statement
    return obj


Nick Coghlan
Brisbane, Australia

More information about the Python-Dev mailing list