Values and objects

Chris Angelico rosuav at gmail.com
Sun May 11 01:22:23 EDT 2014


On Sun, May 11, 2014 at 3:11 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Nonsense. Look at the original examples again, more closely. Here they
> are again, this time with comments:
>
> def test():
>     if False: spam = None  # Dead code, never executed.
>     d = locals()
>     d['spam'] = 23  # Not a normal assignment.
>     return spam
>
> def test():
>     locals()['spam'] = 42  # Not a normal assignment.
>     return spam
>     spam = None  # Dead code.
>
>
> The *only* purpose of the dead code in the two test() functions is to
> force the compiler to use LOAD_FAST (or equivalent) rather than
> LOAD_GLOBAL.

In a C-like language, locals are created by a declaration, and
assigned a value separately. In Python, locals are created by the
presence of assignment within the function, which in simple cases
coincides with giving the value to it; but guarding the assignment
with "if False" prevents the giving of the value, while still being an
assignment for the sake of creating a local variable. Same if the
assignment happens further down, or even in the same statement ("spam
= spam"). It's still an assignment, so it has the declarative effect
of telling the compiler "this is now local, unless declared
global/nonlocal". It's that declaration that creates the variable, not
changing locals().

ChrisA



More information about the Python-list mailing list