Bengt Richter bokr at
Fri Jul 25 16:21:18 CEST 2003

On 25 Jul 2003 00:54:38 -0700, Paul Rubin <> wrote:
>I think a much better solution would involve a language extension,
>maybe a macro in some hypothetical macro extension for Python.  E.g.
>    with f = open(frob):
>      [do stuff with f]
>could be equivalent to:
>   f = open(frob)
>   try:
>     [do stuff with f]
>   finally:
>     f.done()                   # calls f.close()
>     del f
>"done" here is a generic method that gets called on exiting a "with"
First reaction == +1, but some questions...

1) Is f.done() really necessary? I.e., doesn't an explicit del f take care of it
   if the object has been coded with a __del__ method? I.e., the idea was to get
   the effect of CPython's immediate effective del on ref count going to zero, right?

2) how about with two files (or other multiple resources)?

    with f1,f2 = file('f1'), file('f2'):
        [do stuff with f1 & f2]

What is the canonical expansion?

    f1 = file('f1')
        f2 = file('f2')
            [do stuff with f1 & f2]
            del f2  # leaving f2.done() to f2.__del__
        del f1 # ditto-like
or ??

Also, what about the attribute version, i.e.,

    ob.f = file(frob)
      [do stuff with ob.f]
      del ob.f # calls f.__del__, which calls/does f.close()

I.e., ob.f = something could raise an exception (e.g., a read-only property)
*after* file(frob) has succeeded. So I guess the easiest would be to limit
the left hand side to plain names... 

Note that that restriction does not apply e.g. to a for loop construct:

 >>> class SE(object):
 ...     def _setp(self, val): print 'Side effect:', val
 ...     p = property(None,_setp)
 >>> se = SE()
 >>> for se.p in range(5): pass
 Side effect: 0
 Side effect: 1
 Side effect: 2
 Side effect: 3
 Side effect: 4

Bengt Richter

More information about the Python-list mailing list