How To Get A Variable’s Name As A String In Python

Today we will learn how to get a variable’s name as a string in Python. This is a problem that all new and experienced programmers are still searching for a solution. To do it, we tested effectively by using the local().item() method, and using the dict() and global() method. Please read to the end of the articles to know how we can do it.

To Get A Variable’s Name As A String in Python

Using the local() and item() method

To get a variable’s name in Python, you can use the local() method to return the current local symbol table’s dictionary and then call the item() method to return a view object. Then we get the first item in the list of variables by using [0].

Code Example

Let’s see the code example below.

name = "Python"
version = "3.11.1"

# Using local() and item() function
varName = [ i for i, j in locals().items() if j == version][0]

print("The variable name is:", varName) 

Output

The variable name is: version

Using the dict() constructor and global() method

The following way is using the dict() constructor to create a dictionary in Python and call the globals method to get all variables in your code. Then we loop to all variables. If it equals version, we take a variable name out.

Example

name = "Python"
version = "3.11.1"

# Using dict() constructor and globals method
variables = dict(globals())
for name in variables:
    if variables[name] is version:	
        varName = name
        break

print("The variable name is: ", varName) 

Output

The variable name is: version

Using the equal sign and split() method

The last way is using the equal sign and split() method, The split() method is used to split the string into a list. We call the equal sign {version=} to get all variable names equal version and call the split() method, then get the first element by using [0].

Example

name = "Python"
version = "3.11.1"

# Using equal sign and split() method
variables = f'{version=}'.split('=')[0]

print("The variable name is: ", variables)

Output

The variable name is: version

Summary

Throughout the article, we introduce three methods to get a variable’s name as a string in Python, but using the local() and item() method is the best way to do it. Leave your comment here if you have any questions about this article.

Thank you for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *