[Python-ideas] Is this PEP-able? "with" statement inside genexps / list comprehensions

Neil Girdhar mistersheik at gmail.com
Sat Aug 11 19:59:09 EDT 2018



On Monday, July 30, 2018 at 3:55:25 PM UTC-4, Kyle Lahnakoski wrote:
>
> Rudy,
>
> I think your proposal may be very specific to iterable context managers;
>

I don't think his proposal is specific to iterable context managers.  You 
can have a with clause that is used in a following for clause. 

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... at python.org <javascript:>
> > https://mail.python.org/mailman/listinfo/python-ideas
> > Code of Conduct: http://python.org/psf/codeofconduct/
>
> _______________________________________________
> Python-ideas mailing list
> Python... at python.org <javascript:>
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180811/0f5e44f5/attachment.html>


More information about the Python-ideas mailing list