On Mon, Jan 27, 2014 at 2:01 PM, Danny Yoo <d...@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 _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor