[Tutor] When is = a copy and when is it an alias
eryksun
eryksun at gmail.com
Mon Jan 27 22:00:15 CET 2014
On Mon, Jan 27, 2014 at 2:01 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
> And variable binding itself can even have a slightly
> different meaning, depending on whether the surrounding context is a
> function definition or not, establishing a local or global variable
> binding. Whew!
Name binding is local unless you tell Python otherwise by declaring a
name to be global (also nonlocal in 3.x). CPython, for example,
compiles top-level module code to use the STORE_NAME instruction,
which stores to the locals mapping of the current frame. If the name
is declared global, it instead uses STORE_GLOBAL.
Module-level code is flagged to create a frame for which locals and
globals are the same dict. You could, however, exec code using
separate dicts for locals and globals:
src = r'''
global x
x = 0
y = 1
'''
gvars, lvars = {}, {}
exec src in gvars, lvars
####
>>> sorted(gvars)
['__builtins__', 'x']
>>> sorted(lvars)
['y']
CPython bytecode:
>>> code = compile(src, '<str>', 'exec')
>>> dis.dis(code)
3 0 LOAD_CONST 0 (0)
3 STORE_GLOBAL 0 (x)
4 6 LOAD_CONST 1 (1)
9 STORE_NAME 1 (y)
12 LOAD_CONST 2 (None)
15 RETURN_VALUE
More information about the Tutor
mailing list