On Sat, May 18, 2019 at 8:17 PM Yonatan Zunger <zun...@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.
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to