[Python-ideas] Proposal: Allowing any variable to be used in a 'with... as...' expression

David Mertz mertz at gnosis.cx
Sat May 18 21:40:07 EDT 2019


On Sat, May 18, 2019 at 8:17 PM Yonatan Zunger <zunger at humu.com> wrote:

> Instead, we should permit any expression to be used. If a value does not
> expose an __enter__ method, it should behave as though its __enter__
> method is return self; if it does not have an __exit__ method, it should
> behave as though that method is return False.
>

I'm not sure why you would want this.  But it is really easy to implement
with a named function already.  I think it would be better to experiment
with a wrapper function first, maybe put it on PyPI, before changing the
language for something whose purpose is unclear (to me).

I think you probably mean something other than what you actually write.  It
doesn't really make sense for "any expression" as far as I can tell.  What
would it possibly mean to write:

with (2+2) as foo:
    print(foo)

But anyway, my toy simple implementation which satisfies the stated
requirement:

>>> from contextlib import contextmanager
>>> @contextmanager
... def zungerfy(obj):
...     if hasattr(obj, '__enter__'):
...         yield obj.__enter__()
...     else:
...         yield obj
...     if hasattr(obj, '__exit__'):
...         obj.__exit__()
...
>>> with zungerfy(Foo(42)) as foo:
...     print("Hello", foo.val)
...
...
Hello 42
>>> with zungerfy(open('README.md')) as foo:
...     print("Hello", foo.readline())

...
Hello ## About the course


-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190518/ea923900/attachment.html>


More information about the Python-ideas mailing list