No macros in Python

Samuele Pedroni pedronis at bluewin.ch
Tue Dec 17 10:56:28 EST 2002


I would support such a proposal.

"Michael Hudson" <mwh at python.net> ha scritto nel messaggio
news:7h33coweo86.fsf at pc150.maths.bris.ac.uk...
> 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.

maybe we could do with a contextual keyword, and that would also underline
that this is a 'try' form:

try with <exp>:
  <suite>

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

For completeness I think there could be also an option in the design
solution space using generators (a bit along Beni Cherniavsky's idea ) but
avoiding the need to support yield inside try finally - I don't think that
that could ever have a clean semantics -, namely:

try with <expr>:
 <suite>

would be equivalent to:

_x = <expr>
_x.next()
try:
 <suite>
finally:
 _x.next()

So one could write:

def locked(lock):
  lock.acquire()
  yield None
  lock.release()
  yield None

and use it as such:

try with locked(lock):
  ...

this does not require do introduce and pick new special names and that would
count as flexibility, has different performance trade-offs :), but the need
for the second yield and in general is a bit obscure.

regards.









More information about the Python-list mailing list