For review: PEP 343: Anonymous Block Redux and Generator Enhancements
Andrew Dalke
dalke at dalkescientific.com
Sat Jun 4 17:46:55 EDT 2005
Steven Bethard wrote:
> Ahh, so if I wanted the locking one I would write:
>
> with locking(mutex) as lock, opening(readfile) as input:
> ...
That would make sense to me.
> There was another proposal that wrote this as:
>
> with locking(mutex), opening(readfile) as lock, input:
> ...
>
> which is what was confusing me. Mirroring the 'as' from the import
> statement seems reasonable.
Ahh, you're right. That was an earlier proposal.
>
> But it doesn't address my other concern, namely, is
>
> with locking(mutex), opening(readfile) as input:
> ...
>
> equivalent to the nested with-statements, e.g.:
I would think it's the same as
with locking(mutex):
with opening(readfile) as input:
...
which appears to map to the first of your alternatives
> Or is it equivalent to something different, perhaps:
>
> _locking = locking(mutex)
> _opening = opening(readfile)
> _exc = (None, None, None)
> _locking.__enter__()
> input = _opening.__enter__()
> try:
> try:
> ...
> except:
> _exc = sys.exc_info()
> raise
> finally:
> _opening.__exit__(*exc)
> _locking.__exit__(*exc)
That wouldn't work; consider if _opening.__enter__() raised
an exception. The _locking.__exit__() would never be called,
which is not what anyone would expect from the intent of
this PEP.
> Or maybe:
>
> _locking = locking(mutex)
> _opening = opening(readfile)
> _exc = (None, None, None)
> _locking.__enter__()
> input = _opening.__enter__()
Same problem here
> finally:
> # same order as __enter__ calls this time!!
> _locking.__exit__(*exc)
> _opening.__exit__(*exc)
and the order would be wrong since consider multiple
statements as
with server.opening() as connection, connection.lock(column) as C:
C.replace("X", "Y")
The inner with depends on the outer and must be closed
in inverted order.
> And if it *is* just equivalent to the nested with-statements, how often
> will this actually be useful? Is it a common occurrence to need
> multiple with-statements? Is the benefit of saving a level of
> indentation going to outweigh the complexity added by complicating the
> with-statement?
Agreed.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list