How To Print A Variable's Name In Python
Last Updated :
10 Dec, 2025
In Python, you may sometimes want to know or display the name of a variable for example, when debugging, logging, or improving code readability. Python does not provide a built-in way to retrieve a variable’s name directly, but with some clever approaches, it is possible to identify a variable by its reference in the code.
Below are several techniques to print the name of the variable:
Using locals() Function
locals() function returns a dictionary of the current local scope. By searching this dictionary, you can find which local variable references a specific value. This is useful for variables defined inside a function or the current block.
Python
def fun(var):
name = [k for k, v in locals().items() if v is var][0]
print(f"Variable name using locals(): {name}")
x = 42
fun(x)
OutputVariable name using locals(): var
Using globals() Function
The globals() function returns a dictionary of all global variables in the current module. This method is ideal for variables defined at the top level of your script or notebook.
Python
def fun(var):
name = [k for k, v in globals().items() if v is var][0]
print(f"Variable name using globals(): {name}")
y = "Hello, World!"
fun(y)
OutputVariable name using globals(): y
Using a Namespace Directly
You can search any dictionary that represents a namespace, such as locals() or globals(), to find a variable by its value. This approach is flexible and allows you to choose the scope to search in.
Python
def fun(var, namespace):
name = [k for k, v in namespace.items() if v is var][0]
print(f"Variable name using namespace dict: {name}")
z = [1, 2, 3]
fun(z, locals())
OutputVariable name using namespace dict: z
Using inspect Module
inspect module allows you to examine the calling frame, which means you can look into the local variables of the function or scope that called your code. This is the most robust method when working across different scopes.
Python
import inspect
def fun(var):
f1 = inspect.currentframe()
try:
f2 = f1.f_back.f_locals
v1 = [name for name, value in f2.items() if value is var][0]
print(f"Variable name: {v1}")
finally:
del f1
var = 42
fun(var)
Related Articles:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice