Python handles globals badly.

Ian Kelly ian.g.kelly at gmail.com
Fri Sep 11 11:27:10 EDT 2015


On Fri, Sep 11, 2015 at 9:15 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Sep 12, 2015 at 1:03 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>>> 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".
>
> *inside a function*
>
>>>> def f():
> ...    exec("x = 42")
> ...    print(x)
> ...
>>>> x = 231
>>>> f()
> 231

Ah, I didn't parse the "inside a function" as applying to that clause,
but even so, I don't see in what way that is "now illegal". For
example:

>>> x = 231
>>> def f():
...   exec("print(x); x = 42; print(x)")
...   print(x)
...
>>> f()
231
42
231

The exec still happily runs; it's just using its own private locals namespace.

Tangent: does the help for exec need to be updated? It currently reads:

    The globals and locals are dictionaries, defaulting to the current
    globals and locals.  If only globals is given, locals defaults to it.

Which would seem to indicate that if called from within a function
with no globals or locals, the locals from the function would be used.



More information about the Python-list mailing list