[Python-ideas] Is this PEP-able? "with" statement inside genexps / list comprehensions
Kyle Lahnakoski
klahnakoski at mozilla.com
Mon Jul 30 15:54:19 EDT 2018
Rudy,
I think your proposal may be very specific to iterable context managers;
in which case, make a method that makes that assumption:
> def iter_with(obj):
> with obj as context:
> yield from context
and use it
> g = (
> f.read()
> for fn in filenames
> for f in iter_with(open(fn))
> )
On 2018-07-30 15:15, Rudy Matela wrote:
> Hello,
>
> Do you think it would be nice to allow with statements inside genexps or
> list comprehensions? The functions __enter__ and __exit__ would be
> automatically called as iterables are traversed. I am thinking of
> drafting a PEP about this. Examples:
>
>
> This
>
> g = (f.read() for fn in filenames with open(fn) as f)
>
> would be equivalent to the following use of a generator function:
>
> def __gen():
> for fn in filenames:
> with open(fn) as f:
> yield f.read()
> g = __gen()
>
>
> This
>
> list = [f.read() for fn in filenames with open(fn) as f]
>
> would be equivalent to the following:
>
> list = []
> for fn in filenames:
> with open(fn) as f:
> list.append(f.read())
>
> --
> Rudy
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
More information about the Python-ideas
mailing list