Python dynamic variable name string

While programming in python, there are several instances when we might need to convert a string to a variable name. For instance, consider that we need to take some user data as input where the user needs to enter some field names and their corresponding values. We will need to convert the field names to a variable so that we can assign values to them. In this article, we will discuss different ways to convert an input string to a variable name in python.

Table of Contents

  1. String and Variable in Python
  2. How to Access Variable Names in Python?
  3. Convert String Into Variable Name in Python Using the locals() Method
  4. Convert String Into Variable Name in Python Using the globals() Method
  5. String Into Variable Name in Python Using the vars() Function
  6. Convert String Into Variable Name in Python Using the exec() Function
  7. Convert String Into Variable Name in Python Using the setattr() Function
  8. Conclusion

A variable in python is a reference to an object in the memory. We use variables in python to handle different types of values. When we assign a value to a python variable, the interpreter creates a python object for that value. After that, the variable name refers to the memory location. You can define a variable in python as shown in the following python program.

myVar = 5
print("The value in myVar is:", myVar)

Output:

Python dynamic variable name string

The value in myVar is: 5

A python string is a literal contained within single quotes or double-quotes.  We can also define strings using triple quotation marks. We can define a string value and assign it to a string variable as shown in the following example.

myStr = "PythonForBeginners"
print("The value in myStr is:", myStr)

Output:

The value in myStr is: PythonForBeginners

In the above example, we have created a variable myStr. Then, we have assigned the string “PythonForBeginners” to myStr.

How to Access Variable Names in Python?

We can access the variable names in python using the globals() function and the locals() function. 

The globals() function, when executed, returns a dictionary that contains all the variable names as string literals and their corresponding values. It is a global symbol table that contains all the names defined in the global scope of the program. You can observe this in the following python code.

myStr = "PythonForBeginners"
myNum = 5
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)

Output:

The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fe3bfa934c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}

In the above example, you can observe that the dictionary returned by the globals() function contains some default values as well as the variables defined by us. 

The globals() function returns the dictionary that only contains the global variables as its key. When we define a variable inside a function or other inner scopes, we cannot access variables defined inside that scope using the globals() function. For example, look at the following code.

def myFun():
    funvar1 = "Aditya"
    funVar2 = 1117
    print("I am in myFun. The variables in myFun are:")
    print(funvar1, funVar2)


myStr = "PythonForBeginners"
myNum = 5
myFun()
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)

Output:

I am in myFun. The variables in myFun are:
Aditya 1117
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f9d18bb24c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': , 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}

Process finished with exit code 0

In the above example, we have defined funvar1 and funvar2 in the function myFun. However, these variables are not present in the global symbol table.

Even if we execute the globals() function in the function myFun, the variables defined in myFun won’t be included in the global symbol table. You can observe this in the following example.

def myFun():
    funvar1 = "Aditya"
    funVar2 = 1117
    print("I am in myFun. The variables in myFun are:")
    print(funvar1, funVar2)
    print("The variables in global scope and their values are:")
    myVars = globals()
    print(myVars)


myStr = "PythonForBeginners"
myNum = 5
myFun()

Output:

I am in myFun. The variables in myFun are:
Aditya 1117
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7eff3f70d4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': , 'myStr': 'PythonForBeginners', 'myNum': 5}

To print the variable names defined inside a function, we can use the locals() function.

The locals() function, when invoked inside a function or other inner scope, return a dictionary in which the variable names and their associated values are present as a key-value pair.

You can use the print statement to print the dictionary as shown below.

def myFun():
    funvar1 = "Aditya"
    funVar2 = 1117
    print("I am in myFun. The variables in myFun are:")
    print(funvar1, funVar2)
    print("The variables in local scope of myFun and their values are:")
    myVars = locals()
    print(myVars)


myStr = "PythonForBeginners"
myNum = 5
myFun()

Output:

I am in myFun. The variables in myFun are:
Aditya 1117
The variables in local scope of myFun and their values are:
{'funvar1': 'Aditya', 'funVar2': 1117}

In the above example, you can observe that the dictionary returned by the locals() function contains the variables defined inside myFun.

The locals() function, when executed in the global scope, prints the dictionary containing global variables and their values. You can observe this in the following example.

def myFun():
    funvar1 = "Aditya"
    funVar2 = 1117
    print("I am in myFun. The variables in myFun are:")
    print(funvar1, funVar2)


myStr = "PythonForBeginners"
myNum = 5
myFun()
print("The variables in the global scope and their values are:")
myVars = locals()
print(myVars)

Output:

I am in myFun. The variables in myFun are:
Aditya 1117
The variables in the global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fd4fec2e4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': , 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}

Now that we have discussed how we can access variable names in python, let us now discuss how we can create dynamic variables and define dynamic variable names in python. For this, there are various ways that we will discuss one by one.

Convert String Into Variable Name in Python Using the locals() Method

As we have seen in the previous section, the python interpreter stores the variable names and their values in a symbol table in the form of a dictionary. If we are given a string as input in our program, we can define a variable name with the string by adding the input string as a key into the symbol table. We can add a single character, numeric values, or strings as the associated value to the variable. 

To convert the string to a variable name, we will follow the following steps.

  • First, we will obtain the dictionary that contains the symbol table using the locals() function. The locals() function, when executed, returns the symbol table of the current scope.
  • Once we obtain the symbol table, we will add the string name as a key and the value of the variable as the associated value using the subscript notation. 
  • After adding the key-value pair to the symbol table, the variable is created with the given string name and the associated value. 

You can observe this using this simple example.

myStr = "domain"
print("The string is:",myStr)
myVars = locals()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))

Output:

The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f2fb9cb44c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com

In the above example, we have used the subscript notation to make changes to the symbol table. Instead of using the subscript notation to add the new string value as a key to the symbol table, you can use the __setitem__() method. 

The __setitem__() method, when invoked on a python dictionary, takes a string literal as its first argument and the value associated with the new variable name as the second argument. After execution, the string and the value are added to the dictionary as a key-value pair in the dictionary. 

As the symbol table returned by the locals() method is also a dictionary, we can use the __setitem__() method to convert string to a variable name in python as shown below.

myStr = "domain"
print("The string is:", myStr)
myVars = locals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))

Output:

The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f77830734c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com

The above approach using the locals() method only makes the changes in the current scope, Therefore, it is useful when we want to convert a string to a variable name in a local scope like a function. If you only want to change the symbol table of a function, you can use the locals() function to convert a string to a variable name in python as follows.

def myFun():
    myStr = "domain"
    print("The string is:", myStr)
    myVars = locals()
    myVars.__setitem__(myStr, "pythonforbeginners.com")
    print("The variables are:")
    print(myVars)


myFun()

Output:

The string is: domain
The variables are:
{'myStr': 'domain', 'domain': 'pythonforbeginners.com'}

If you want to make changes in the global symbol table to convert a python string to a global variable name, you can execute the locals() function in the global scope. After that, you can add variables using the subscript notation or the __setitem__() method as shown in the previous examples.

Convert String Into Variable Name in Python Using the globals() Method

If you want to convert a string to a global variable when you are inside a function, you cannot do it using the locals() function. For this task, you can use the globals() function.

When executed, the globals() function returns the global symbol table. You can make changes to the global symbol table inside any scope to convert a string to a global variable name. For this, we will perform the following steps.

  • First, we will obtain the global symbol table using the globals() function. The globals() function, when executed, returns the global symbol table as a dictionary.
  • Once we obtain the symbol table, we will add the string name as a key and the value of the variable as the associated value using the subscript notation for dictionaries. 
  • After adding the key-value pair to the symbol table, the variable is created with the given string name and the associated value. 

After executing the above steps, we can convert a string to a global variable. You can observe this in the following example.

myStr = "domain"
print("The string is:",myStr)
myVars = globals()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))

Output:

The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7ff717bd34c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com

Instead of using the subscript notation, you can use the __setitem__() method with the globals() function to convert a string to a global variable name in python as shown below.

myStr = "domain"
print("The string is:", myStr)
myVars = globals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))

Output:

The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fc4c62ba4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com

String Into Variable Name in Python Using the vars() Function

Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function. When executed in a function or an inner scope, the vars() function behaves as the locals() function.

To convert a string into a variable name using the vars() function in the global scope, we will use the following steps.

  • Using the vars() function, we will obtain the dictionary containing the variable names in the global scope. 
  • After obtaining the dictionary, we will add the string name as a key and the value of the variable as the associated value using the subscript notation for dictionaries. 
  • Once we add the string and associated value to the dictionary, the variable is created in the global scope.

Following is the sample code that executes the above steps to convert a string to a variable name in python.

myStr = "domain"
print("The string is:",myStr)
myVars = vars()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))

Output:

The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb9c6d614c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com

You can also use the __setitem__() method on the dictionary instead of the subscript notation to create the variable as shown in the following example.

myStr = "domain"
print("The string is:", myStr)
myVars = vars()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))

Output:

The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb5e21444c0>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com

To convert a string to a variable name in a local scope like a function using the vars() function, you can execute the same steps that we used to create a global variable using the locals() function. You can observe this in the following example.

def myFun():
    myStr = "domain"
    print("The string is:", myStr)
    myVars = vars()
    myVars.__setitem__(myStr, "pythonforbeginners.com")
    print("The variables are:")
    print(myVars)


myFun()

Output:

The string is: domain
The variables are:
{'myStr': 'domain', 'domain': 'pythonforbeginners.com'}

In the previous sections, we have directly changed the symbol table to convert a string to a variable name. However, this is not the best way to perform the task.

Let us now discuss how we can convert a string to a variable name in python without directly changing the symbol table.

Convert String Into Variable Name in Python Using the exec() Function

We can use the exec() function for the dynamic execution of a python statement. The exec() function takes a python statement in the form of a string as an input argument. Then, the python statement is executed as if it were a normal python statement written in the code. For example, we can define a variable x with the value 5 using the exec() function as shown below.

myStr = "x=5"
exec(myStr)
print(x)

Output:

5

To convert a string to a variable name using the exec() function, we will use string formatting. We can do the entire process using the following steps.

  • First, we will define a variable myStr that contains the original string that we need to convert into a variable name.
  • After that, we will create a string myTemplate in the format “{} = {}"”. Here, we will use the first placeholder for the string name, and the second placeholder for the value of the variable that we will create from the string variable.
  • After creating the string with placeholders, we will invoke the format() method on myTemplate with myStr as the first input argument and the value for the variable created from myStr as the second input argument. 
  • Once executed, the format() method will return a string that looks like a python statement with myStr as the variable name to which the given value is assigned.
  • After obtaining the string containing the python statement, we will pass it to the exec() function. 
  • Once the exec() function is executed, the variable will be created with the string myStr as the variable name.

You can observe this in the following example.

myStr = "domain"
myVal = "pythonforbeginners.com"
myTemplate = "{} = \"{}\""
statement = myTemplate.format(myStr, myVal)
exec(statement)
print(domain)

Output:

pythonforbeginners.com

Convert String Into Variable Name in Python Using the setattr() Function

Instead of using the exec() function, we can also use the setattr() function to convert a string into a variable name in python. 

The setattr() function takes a python object as its first input argument, the attribute (variable) name as the second input argument, and the value of the attribute as the third input argument. After execution, it adds the attribute to the object.

To convert a string to a variable name using the setattr() function, we first need to obtain the current scope as a python object so that we can add the variable as an attribute to it. For this, we will have to perform two tasks.

  • First, we need to get the name of modules that are currently loaded in the program.
  • After that, we need to find the module that is currently being executed, i.e. the current scope.

To find the name of the modules that are currently loaded in the memory, we will use the sys.modules attribute. The sys.modules attribute contains a dictionary with mapping of module names to modules that have already been loaded. 

After obtaining the dictionary, we need to find the current module. For this, we will use the __name__ attribute. __name__ is a built-in attribute that evaluates to the name of the current module. 

The __name__ attribute is also present in the symbol table. You can find the name of the current module using the __name__ attribute as shown below.

print("The current module name is:")
print(__name__)

Output:

The current module name is:
__main__

Here, you can see that we are currently in the __main__ module.

After obtaining the name of the current module using the __name__ attribute, we will obtain the current module object using the subscript notation on sys.modules attribute. 

After obtaining the current module, we will convert the string to a variable name using the setattr() function. For this, we will pass the current module as the first input argument, the string as the second input argument, and the value of the variable as the third input argument to the setattr() function. After execution of the setattr() function, the variable will be created in the current scope with the input string as the variable name.

You can observe this in the following example.

import sys

myStr = "domain"
myVal = "pythonforbeginners.com"
moduleName = __name__
currModule = sys.modules[moduleName]
setattr(currModule, myStr,myVal)
print(domain)

Output:

pythonforbeginners.com

Conclusion

In this article, we have discussed different ways to convert a string to a variable name in python. Of all the approaches discussed in this article, I would suggest you use the approach with exec() method. This is so because there are several reserved keywords that we cannot use as a variable name. The keywords are used for different tasks to run the programs. However, if we are directly changing the symbol table, it is possible that we might change the value associated with a keyword. In such as case, the program will run into an error. Therefore, try to use the approach with the exec() function to convert a string to a variable name in python. 

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

How do you use a string as a variable name in Python?

String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.

How do you use dynamic variable names in Python?

Use a Dictionary to Create a Dynamic Variable Name in Python It is written with curly brackets {} . In addition to this, dictionaries cannot have any duplicates. A dictionary has both a key and value, so it is easy to create a dynamic variable name using dictionaries.

How do you pass a variable dynamically in Python?

You can create a dict using the variable and then unpack while passing it to the function: list_of_variable_names = ['myMsg','anotherMessages'] for name in list_of_variable_names: helloWorld(**{name: '...'})

How do you assign a variable to a name in Python?

Rules for Python variables:.
A variable name must start with a letter or the underscore character..
A variable name cannot start with a number..
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
Variable names are case-sensitive (age, Age and AGE are three different variables).