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

Rudy Matela rudy at matela.com.br
Mon Jul 30 15:15:17 EDT 2018


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


More information about the Python-ideas mailing list