Python 3 removes name binding from outer scope

Chris Angelico rosuav at gmail.com
Tue Jul 25 16:06:02 EDT 2017


On Wed, Jul 26, 2017 at 4:36 AM, eryk sun <eryksun at gmail.com> wrote:
> On Tue, Jul 25, 2017 at 8:43 AM, Chris Angelico <rosuav at gmail.com> wrote:
>>>> I'm not actually sure what happens if you use a global declaration at
>> top level. Is it ignored? Is it an error?
>> It isn't ignored, but it shouldn't make a difference since normally at
> module level locals and globals are the same. It makes a difference in
> an exec() that uses separate locals and globals dicts. For example:
>> >>> exec('print(x)', {'x':'G'}, {'x':'L'})
> L
> >>> exec('global x; print(x)', {'x':'G'}, {'x':'L'})
> G

Thanks. Of course, that doesn't change the fact that it'll look very
odd - but at least it won't cause a problem. Now, if you wanted to
write Py2/Py3 compatibility code inside a function, you'd have issues,
because you can't use nonlocal in Py2... but that's a separate issue.
Hmm. Aside from messing around with exec, is there any way to have a
local and a global with the same name, and use the global? You could
do it with a nonlocal:
x = "G"
def f():
 x = "L"
 def g():
 global x
 print(x)
 g()
but is there any way to engineer this actual situation without exec?
ChrisA


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /