Quick survey: locals in comprehensions (Python 3 only)

Chris Angelico chris.angelico at 1
Sun Jun 24 17:16:00 EDT 2018


From: Chris Angelico <rosuav at gmail.com>

On Sun, Jun 24, 2018 at 4:08 PM, Jim Lee <jlee54 at gmail.com> wrote:
> There are three locals:  a, b, and result.  Since result cannot be assigned
> a value until the list comp has been evaluated, I would expect the comp to
> return a value of "None" for result.  An argument could also be made for [1,
> 2, []], but one thing I would *not* expect is [1, 2] or [2, 1]...

Ahh, I see what you mean. Thing is, there's a definite difference between "this
 is None" and "this doesn't have a value". The latter situation is indicated by
 simply not having the local.

def f():
    print("; ".join("%s=%r" % x for x in locals().items()))
    a = 1
    print("; ".join("%s=%r" % x for x in locals().items()))
    b = 2
    print("; ".join("%s=%r" % x for x in locals().items()))

The results may surprise you, or may not.

This part has nothing to do with the behaviour of locals inside a
comprehension, though. The important part is that, like me, you would like
comprehensions to represent a block of code inside the current function, not an
 implicit nested function.

ChrisA

--- BBBS/Li6 v4.10 Toy-3
 * Origin: Prism bbs (1:261/38)



More information about the Python-list mailing list