Open In App

Get Variable Name As String In Python

Last Updated : 01 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Getting a variable name as a string in Python means finding the label that points to a specific value. For example, if x = "Python", we can loop through globals() or locals() and compare values using the is operator to find that the name x points to "Python". Let’s explore some simple and effective methods to achieve this.

Using globals()

globals() returns a dictionary of all variables in the global scope. If we loop through it, we can find which variable matches a specific value.

Python
x = "Python"
for name, value in list(globals().items()):
    if value is x:
        print(name)
        break

Output
x

Explanation: globals() function returns a dictionary of global variables. Here, x is assigned "Python" and by iterating over list(globals().items()), the code identifies and prints the variable name that references the same object as x using the is operator.

Using locals()

Similar to globals(), locals() returns a dictionary of variables, but for the current function or block.

Python
x = "Python"
for name, value in list(locals().items()):
    if value is x:
        print(name)
        break

Output
x

Explanation: locals() function returns a dictionary of variables in the current local scope. Here, x is set to "Python" and locals().items() is converted to a list to safely iterate and find the variable name using the is operator.

Using a Custom Class Wrapper

This method is different: you create a class where you explicitly assign the variable name as a property when creating the variable.

Python
class Var:
    def __init__(self, name, value):
        self.name = name
        self.value = value

x = Var("x", 42)
print(x.name)

Output
x

Explanation: class Var manually store a variable’s name and value. When you create an object like x = Var("x", 42), the name and value are stored as attributes. Accessing x.name directly returns the variable name "x".

Using inspect

inspect lets us dig into the call stack. We use it here to look at the frame where the variable is defined and fetch local variable names.

Python
import inspect
x = 50
frame = inspect.currentframe().f_back or inspect.currentframe()
for name, val in list(frame.f_locals.items()):
    if val is x:
        print(name)
        break

Output
x

Explanation: inspect module retrieves local variables from the current or previous frame, allowing you to find a variable's name by comparing values using is.

Related articles


Next Article

Similar Reads