python contextmanagers and ruby blocks

Alia K alia_khouri at yahoo.com
Sat Feb 21 16:31:07 EST 2009


Aahz wrote:
> Longer answer: the way in Python to achieve the full power of Ruby
> blocks is to write a function.

You are most likely right... there is probably no need to introduce
ruby-like blocks to python where iteration comes naturally with list
comprehensions and generators. But for the simple case of entering a
block of code as one does with @contextmanager I suppose it would be
nice to make a generator with a single yield statement a
contextmanager by default such that:

>>> def g():
...     print "a"
...     yield
...     print "b"
...
>>> with g():
...     print "c"
...
a
c
b

would be equivalent to

>>> from __future__ import with_statement
>>> from contextlib import contextmanager
>>> @contextmanager
... def g():
...     print "a"
...     yield
...     print "b"
...
>>> with g():
...     print "c"
...
a
c
b

but then again, I suppose "explicit is better than implicit"...

AK




More information about the Python-list mailing list