Python handles globals badly.

Ian Kelly ian.g.kelly at gmail.com
Fri Sep 11 17:03:41 CEST 2015


On Fri, Sep 11, 2015 at 2:42 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, 11 Sep 2015 10:35 am, Ian Kelly wrote:
>
>> On Thu, Sep 10, 2015 at 4:25 PM,  <tdev at freenet.de> wrote:
> [...]
>>> So the compiler knows the distiction between global and local already.
>>
>> As we've said before, it doesn't. The compiler's current rules are
>> fairly simple:
>>
>> 1) If it's in the function's argument list, it's an argument (and
>> therefore local).
>> 2) If it's explicitly declared global, then it's global.
>> 3) If it's never assigned within the function, then it's global.
>
> Almost. If it's never assigned within the function, then it is looked up
> according to the non-local scoping rules:
>
> - closures and enclosing functions (if any);
> - globals;
> - builtins;
>
> in that order.

I excluded non-locals intentionally, but if you want to be pedantic
about it, then that's still not quite right. Non-locals are indeed
identified by the compiler and compiled with the
LOAD_DEREF/STORE_DEREF opcodes (rather than the _GLOBAL and _FAST
variants used by globals and locals, respectively). The compiler
doesn't make any such distinction between globals and builtins
however, as that can only be determined at run-time.

> There's also a bunch of specialised and complicated rules for what happens
> if you make a star import ("from module import *") inside a function, or
> call eval or exec without specifying a namespace. Both of these things are
> now illegal in Python 3.

Huh?

>>> exec("x = 42")
>>> x
42
>>> exec("x = 43", None, None)
>>> x
43

That's in Python 3.4.0. Maybe I don't understand what you mean by
"without specifying a namespace".


More information about the Python-list mailing list