Quick survey: locals in comprehensions (Python 3 only)

Jim Lee jim.lee at 1
Sun Jun 24 00:24:16 EDT 2018


From: Jim Lee <jlee54 at gmail.com>



On 06/23/2018 11:16 PM, Chris Angelico wrote:
> 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
That's why I said an argument could be made for [1, 2, []].Γ  I realize that
NoneType is not the same as no type, but, having not studied the internals of
any particular Python implementation,Γ  I don't know how it builds or
initializes its local symbol table. But, I expected "result" to exist before
the list comprehension was evaluated simply due to left->right parsing.

-Jim

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



More information about the Python-list mailing list