[Python-ideas] PEP 572: Statement-Local Name Bindings

Serhiy Storchaka storchaka at gmail.com
Wed Feb 28 08:49:05 EST 2018


28.02.18 00:27, Chris Angelico пише:
> Example usage
> =============
> 
> These list comprehensions are all approximately equivalent::
> 
>      # Calling the function twice
>      stuff = [[f(x), f(x)] for x in range(5)]

The simplest equivalent of [f(x), f(x)] is [f(x)]*2. It would be worth 
to use less trivial example, e.g. f(x) + x/f(x).

>      # Helper function
>      def pair(value): return [value, value]
>      stuff = [pair(f(x)) for x in range(5)]
> 
>      # Inline helper function
>      stuff = [(lambda v: [v,v])(f(x)) for x in range(5)]
> 
>      # Extra 'for' loop - see also Serhiy's optimization
>      stuff = [[y, y] for x in range(5) for y in [f(x)]]
> 
>      # Expanding the comprehension into a loop
>      stuff = []
>      for x in range(5):
>          y = f(x)
> stuff.append([y, y])
> 
>      # Using a statement-local name
>      stuff = [[(f(x) as y), y] for x in range(5)]


Other options:

     stuff = [[y, y] for y in (f(x) for x in range(5))]

     g = (f(x) for x in range(5))
     stuff = [[y, y] for y in g]

     def g():
         for x in range(5):
             y = f(x)
             yield [y, y]
     stuff = list(g)

Seems the two last options are generally considered the most Pythonic. 
map() and itertools can be helpful in particular cases.



More information about the Python-ideas mailing list