Contrary to other answers already posted you cannot modify locals() directly 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

Modifying locals() is undefined. Outside a function when locals() and globals() are the same it will work; inside a function it will usually not work.

Use a dictionary, or set an attribute on an object:

d = {}
d['xyz'] = 42
print(d['xyz'])

or if you prefer, use a class:

class C: pass

obj = C()
setattr(obj, 'xyz', 42)
print(obj.xyz)

Edit: Access to variables in namespaces that aren't functions (so modules, class definitions, instances) are usually done by dictionary lookups (as Sven points out in the comments there are exceptions, for example classes that define __slots__). Function locals can be optimised for speed because the compiler (usually) knows all the names in advance, so there isn't a dictionary until you call locals().

In the C implementation of Python locals() (called from inside a function) creates an ordinary dictionary initialised from the current values of the local variables. Within each function any number of calls to locals() will return the same dictionary, but every call to locals() will update it with the current values of the local variables. This can give the impression that assignment to elements of the dictionary are ignored (I originally wrote that this was the case). Modifications to existing keys within the dictionary returned from locals() therefore only last until the next call to locals() in the same scope.

In IronPython things work a bit differently. Any function that calls locals() inside it uses a dictionary for its local variables so assignments to local variables change the dictionary and assignments to the dictionary change the variables BUT that's only if you explicitly call locals() under that name. If you bind a different name to the locals function in IronPython then calling it gives you the local variables for the scope where the name was bound and there's no way to access the function locals 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}
>>>

This could all change at any time. The only thing guaranteed is that you cannot depend on the results of assigning to the dictionary returned by locals().

Answer from Duncan on Stack Overflow
Top answer
1 of 7
92

Contrary to other answers already posted you cannot modify locals() directly 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

Modifying locals() is undefined. Outside a function when locals() and globals() are the same it will work; inside a function it will usually not work.

Use a dictionary, or set an attribute on an object:

d = {}
d['xyz'] = 42
print(d['xyz'])

or if you prefer, use a class:

class C: pass

obj = C()
setattr(obj, 'xyz', 42)
print(obj.xyz)

Edit: Access to variables in namespaces that aren't functions (so modules, class definitions, instances) are usually done by dictionary lookups (as Sven points out in the comments there are exceptions, for example classes that define __slots__). Function locals can be optimised for speed because the compiler (usually) knows all the names in advance, so there isn't a dictionary until you call locals().

In the C implementation of Python locals() (called from inside a function) creates an ordinary dictionary initialised from the current values of the local variables. Within each function any number of calls to locals() will return the same dictionary, but every call to locals() will update it with the current values of the local variables. This can give the impression that assignment to elements of the dictionary are ignored (I originally wrote that this was the case). Modifications to existing keys within the dictionary returned from locals() therefore only last until the next call to locals() in the same scope.

In IronPython things work a bit differently. Any function that calls locals() inside it uses a dictionary for its local variables so assignments to local variables change the dictionary and assignments to the dictionary change the variables BUT that's only if you explicitly call locals() under that name. If you bind a different name to the locals function in IronPython then calling it gives you the local variables for the scope where the name was bound and there's no way to access the function locals 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}
>>>

This could all change at any time. The only thing guaranteed is that you cannot depend on the results of assigning to the dictionary returned by locals().

2 of 7
31

Others have suggested assigning to locals(). This won't work inside a function, where locals are accessed using the LOAD_FAST opcode, unless you have an exec statement somewhere in the function. To support this statement, which could create new variables that are not known at compile time, Python is then forced to access local variables by name within the function, so writing to locals() works. The exec can be out of the code path that is executed.

def func(varname):
    locals()[varname] = 42
    return answer           # only works if we passed in "answer" for varname
    exec ""                 # never executed

func("answer")
>>> 42

Note: This only works in Python 2.x. They did away with this foolishness in Python 3, and other implementations (Jython, IronPython, etc.) may not support it either.

This is a bad idea, though. How will you access the variables if you don't know their name? By locals()[xxx] probably. So why not just use your own dictionary rather than polluting locals() (and taking the chance of overwriting a variable your function actually needs)?

๐ŸŒ
Quora
quora.com โ€บ Is-it-impossible-to-dynamically-create-local-variables-in-Python-3-scripts
Is it impossible to dynamically create local variables in Python 3 scripts? - Quora
Answer: yes, but it still far easier to just put the data into a dictionary. For example : [code]def dynamic_local(): a, b = 2, 3 locals()['c'] = 4 return a + b + locals()['c'] [/code]Notice that you have to use locals() to access your dynamically created variable; and in effect all you are...
๐ŸŒ
Medium
higee.io โ€บ create-variables-dynamically-feat-globals-locals-vars-dcb48cbf399d
Create variables dynamically (feat. globals, locals, vars) - higee
July 23, 2022 - *Since the goal of this post is not to dive into the difference between global and local namespaces, I will just use global in the rest of the post. ... Back to the main story. Now that we have seen that there is a dictionary that holds variable name and its value, maybe we could try adding key/value pair to that dictionary? That is it! We looked into how we could create variables dynamically given a list of strings. After briefly checking when/how Python raises a NameError, I introduced a way to update a dictionary that is in charge of keeping track of names in the module namespace using globals().
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python dynamic variable name
Python Dynamic Variable Name | Delft Stack
December 14, 2023 - Here, the line locals().update({variable_name: value}) is equivalent to creating a local variable dynamically, such as dynamic_var = 'Hello', within the local scope. Finally, we print the value of the dynamically created variable using ...
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ dynamic-ways-creating-variables-python-akhil-pathirippilly-mana
Dynamic ways of creating variables in python
February 11, 2022 - If you initialize num = 1 globally and num=2 locally inside a function , global symbol table will store as previous example while local symbol table will store as locals()['num']=2. Whatever you declare or import with-in the scope of that function only will be stored on locals symbol table ยท Now let's come back to our original scenario of dynamically declaring variables.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-36546.html
Generate Python variables dynamically
March 2, 2022 - For getting data from MySQL and displaying it in my output.php, I dynamically create PHP variables Quote:$i = 0; $j = 0; foreach($allQsdata as $Qsdata) { ++$i; $Qnr = 'Q' . $i; ${'Q'.$i} = $questions;
Find elsewhere
๐ŸŒ
PyTutorial
pytutorial.com โ€บ python-dynamic-variable-creation-using-locals-and-globals
PyTutorial | Python Dynamic Variable Creation Using locals() and globals()
November 21, 2024 - 3. Always document your code when using dynamic variable creation. class DynamicClass: def __init__(self, **kwargs): # Dynamically create class attributes for key, value in kwargs.items(): setattr(self, key, value) # Create instance with dynamic attributes obj = DynamicClass(name="Python", version=3.9) print(obj.name, obj.version)
๐ŸŒ
DEV Community
dev.to โ€บ chintanonweb โ€บ beyond-static-embracing-dynamic-variable-creation-in-python-57ol
Beyond Static: Embracing Dynamic Variable Creation in Python - DEV Community
April 8, 2024 - One way to dynamically create variables in Python is by utilizing the globals() function. This function returns a dictionary representing the current global symbol table, which contains all the variables defined in the global scope.
Top answer
1 of 4
6

Use lists instead of this insanity called variable variables.

def build_ports(portlist)
    ports = []
    for idx, portname in enumerate(portlist):
        ports.append(Port())
        ports[-1].port_method1()
        if idx > 5:
            ports[-1].port_method2()

Instead of using ports[-1], you might instead scrap the unused portname iteration variable and create a local portname = Port(), use that to call the methods and then append it to ports at the end. What is portlist anyway?

2 of 4
3

No, this is not possible. If you look at how Python stores local variables, you can see why.

Global variables are stored in a hash table, which is dynamically-sized, and the names are compiled into hash keys (in Python parlance, interned strings). This makes global lookups comparatively "slow", but since one needs to find globals by name from other compilation units (modules), it's required:

# a.py
x = 3

# b.py
import a
a.x = 4 # b needs to know how to find the same x!

Local variables are stored in a fixed-size array and the names are compiled into array indices.

This can be seen when you look at the bytecode, which has LOAD_FAST and STORE_FAST for locals but LOAD_GLOBAL and STORE_GLOBAL for globals. It also leaks through in the different exceptions you get. Globals trickle up and generate a NameError when not found, but undefined locals are detected by an empty slot, giving an UnboundLocalError.

def foo():
    a
    a = 1
foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in foo
UnboundLocalError: local variable 'a' referenced before assignment

def foo():
    a = 1
foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in foo
NameError: global name 'a' is not defined

Because the array is fixed-size, and the size is computed while compiling the function, you cannot create any additional locals.

If you need more "locals", you'll need to store the values as named attributes of an object or in a dictionary; obviously that will also negate the speed benefits.

๐ŸŒ
Quora
quora.com โ€บ How-can-I-dynamically-create-variables-in-Python
How to dynamically create variables in Python - Quora
Answer (1 of 5): x = 0 For i in range(10): String = โ€œvar%d = %dโ€%(x, x) exec(String) x+=1 Now you have 11 variables
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 3015787 โ€บ how-to-create-a-dynamic-variable-in-python
How to create a dynamic variable in python
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-program-to-create-dynamically-named-variables-from-user-input
Python program to create dynamically named variables from user input - GeeksforGeeks
July 23, 2025 - Here we are using the globals() method for creating a dynamically named variable and later assigning it some value, then finally printing its value. ... # Dynamic_Variable_Name can be # anything the user wants Dynamic_Variable_Name = "geek" ...
๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ top-5-methods-to-dynamically-set-local-variables-in-python
Top 5 Methods to Dynamically Set Local Variables in Python - โ€ฆ
November 23, 2024 - Instead of trying to manipulate locals(), a more reliable approach is to use a dictionary. This allows for easy and dynamic variable assignment: def set_dynamic_variable(): dynamic_dict = {} dynamic_dict['dynamic_var'] = 100 print(dynamic_dict['dynamic_var']) # Successfully prints 100 set_dynamic_variable() Another approach is to create a class and assign attributes dynamically using the setattr() function:
๐ŸŒ
Medium
medium.com โ€บ geekculture โ€บ a-cool-way-to-dynamically-create-variables-in-python-7c20c12f4f23
A Cool Way To Dynamically Create Variables In Python | by Liu Zuo Lin | Geek Culture | Medium
April 17, 2023 - A Cool Way To Dynamically Create Variables In Python When we create variables in Python, these variables are actually stored in a dictionary. And we can get this dictionary using globals(). a = 100 b โ€ฆ
๐ŸŒ
Esri Community
community.esri.com โ€บ t5 โ€บ python-questions โ€บ create-dynamic-variable-from-returned-value โ€บ td-p โ€บ 1185872
Solved: Create dynamic variable from returned value / vari... - Esri Community
July 7, 2022 - You can use __getattr__() and __setattr__() built in methods on global/local namespaces to get/set variables by string name on an object or module. See: https://docs.python.org/3.7/library/functions.html#getattr and https://docs.python.org/...
๐ŸŒ
Codingdeeply
codingdeeply.com โ€บ home โ€บ python: 5 best techniques to generate dynamic variable names
Python: 5 Best Techniques to Generate Dynamic Variable Names - Codingdeeply
February 23, 2024 - Hereโ€™s an illustration of how to make a dynamic variable name using the locals() Method: prefix = "dynamic_" suffix = "_variable" var_num = 1 # Creating dynamic variable name using locals() locals()[prefix + str(var_num) + suffix] = 42 # Accessing ...