No macros in Python

Michael Hudson mwh at python.net
Tue Dec 17 09:04:10 EST 2002


jepler at unpythonic.net writes:

> I'd rather just write 'with lock: suite'.

Right.  Here's a proposal:

with <exp>:
  <suite>

is equivalent to

_x = <exp>
_x.__enter__()
try:
  <suite>
finally:
  _x.__exit__()

Method names can be argued about.  I think they should be __special__
names because they are called by the interpreter, not the
programmer[*].

threading.RLock, for example, gets:

    __enter__ = acquire
    __exit__ = release

added to it's definition.

Everyone in the world writes something like:

class output_to(object):
    def __init__(self, f):
        self.file = f
    def __enter__(self):
        self.saved = sys.stdout
        sys.stdout = self.file
    def __exit__(self):
        sys.stdout = self.saved

so you can do

with output_to(open("/tmp/log", "w")):
    print "hello!"

'with' would have to become a keyword, so that implies a __future__
statement, even though it's kind of hard to see how you would use it
as a name.

I don't think this would be hard to implement.  I'll do a prototype
and a proper PEP after 2.3 is out.

Cheers,
M.
[*] this is a nice just-so story for why .next() is not called
    .__next__().

-- 
7. It is easier to write an incorrect program than understand a
   correct one.
  -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html



More information about the Python-list mailing list