Python 3 removes name binding from outer scope

Steve D'Aprano steve+python at pearwood.info
Tue Jul 25 20:20:55 EDT 2017


On Wed, 26 Jul 2017 06:06 am, Chris Angelico wrote:

> 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?

Use globals['name'].


There's no way to do it with regular name look ups. This doesn't work:


spam = 'outside'

def func():
    spam = 'inside'
    assert spam == 'inside'
    global spam
    assert spam == 'outside'



The problem is that global is a declaration, not an executable statement, and if
it is *anywhere* inside function, it is deemed to apply to the entire function.

Apart from that, you could try hacking the byte-code. It should be a matter of
just replacing LOAD_FAST with LOAD_GLOBAL, I think.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list