Unlike other answers already posted, you cannot directly modify locals() and expect it to work.
>>> def foo(): lcl = locals() lcl['xyz'] = 42 print(xyz) >>> foo() Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> foo() File "<pyshell#5>", line 4, in foo print(xyz) NameError: global name 'xyz' is not defined
Modification of locals() is undefined. Outside the function, when locals() and globals() are the same, it will work; function inside usually doesn't work.
Use a dictionary or set an attribute for an object:
d = {} d['xyz'] = 42 print(d['xyz'])
or if you want, use the class:
class C: pass obj = C() setattr(obj, 'xyz', 42) print(obj.xyz)
Edit : Access to variables in namespaces that are not functions (so modules, class definitions, instances) are usually performed by dictionary lookups (as Sven points out in the comments, there are exceptions, for example classes that define __slots__ ). Local function locators can be optimized for speed, because the compiler (usually) knows all the names in advance, so the dictionary does not exist until you call locals() .
In the C Python implementation, locals() (called from within the function) creates a regular dictionary initialized from the current values ββof local variables. In each function, any number of locals() calls will return the same dictionary, but each locals() call will update it with the current values ββof local variables. This may give the impression that assignment to dictionary elements is ignored (I originally wrote that it was). Changes to existing keys in the dictionary returned with locals() , therefore, continue only until the next call to locals() in the same scope.
In IronPython, everything works differently. Any function that calls locals() inside it uses the dictionary for its local variables, so assignments to local variables change the dictionary and assignments to the dictionary change BUT variables, which is only if you explicitly call locals() in that name. If you associate another name with the locals function in IronPython, then calling it gives local variables for the area where the name was associated, and there is no way to access local functions through it:
>>> def foo(): ... abc = 123 ... lcl = zzz() ... lcl['abc'] = 456 ... deF = 789 ... print(abc) ... print(zzz()) ... print(lcl) ... >>> zzz =locals >>> foo() 123 {'__doc__': None, '__builtins__': <module '__builtin__' (built-in)>, 'zzz': <built-in function locals>, 'foo': <function foo at 0x000000000000002B>, '__name__': '__main__', 'abc': 456} {'__doc__': None, '__builtins__': <module '__builtin__' (built-in)>, 'zzz': <built-in function locals>, 'foo': <function foo at 0x000000000000002B>, '__name__': '__main__', 'abc': 456} >>>
All of this can change at any time. The only thing guaranteed is that you cannot depend on the results of assigning the dictionary returned by locals() .