Sai A Sai A
Updated date May 15, 2023
In this blog, we explore different methods to get the name of a variable as a string in Python. We will discuss the use of globals() and locals() functions, the inspect module, the traceback module, and f-strings.

Introduction:

In Python, a variable name is used to store a value in memory. Sometimes, it is necessary to get the variable name as a string to debug or to use it in a string message. However, Python does not provide a direct way to do this. In this blog, we will discuss multiple ways to get the variable name as a string in Python.

Method 1: Using globals() and locals() functions.

The globals() and locals() functions in Python are used to access the global and local namespace, respectively. We can use these functions to get the name of a variable as a string. Here is the program:

def get_variable_name(variable):
    for name in globals():
        if id(globals()[name]) == id(variable):
            return name
    for name in locals():
        if id(locals()[name]) == id(variable):
            return name
    return None

x = 5
variable_name = get_variable_name(x)
print(variable_name)

Output:

x

In the above program, we have defined a function get_variable_name which takes a variable as input and returns the name of the variable. We are using two for loops to access the global and local namespaces. We are checking if the id of the variable matches with the id of the variables in the namespace. If there is a match, we are returning the name of the variable. Otherwise, we are returning None. In the main program, we have defined a variable x and called the get_variable_name function to get its name as a string. Finally, we are printing the variable name.

Method 2: Using inspect module.

Python provides an inspect module that can be used to get information about objects including the variable name. Here is the program:

import inspect

def get_variable_name(variable):
    frame = inspect.currentframe()
    while frame:
        if variable in frame.f_locals:
            return frame.f_locals[variable]
        frame = frame.f_back
    return None

x = 5
variable_name = get_variable_name(x)
print(variable_name)

Output:

x

In the above program, we have used the inspect.currentframe() function to get the current frame. We are using a while loop to iterate through the frames until we find the frame where the variable is defined. We are checking if the variable is present in the local namespace of the frame. If yes, we are returning the name of the variable. Otherwise, we are moving to the previous frame. If we reach the top of the call stack and still could not find the variable, we are returning None. In the main program, we have defined a variable x and called the get_variable_name function to get its name as a string. Finally, we are printing the variable name.

Method 3: Using the traceback module.

Python provides a traceback module that can be used to get information about the call stack including the variable name. Here is the program:

import traceback

def get_variable_name(variable):
    for line in traceback.format_stack():
        if "in <module>" in line:
            break
        if variable in line:
            return line.split("=")[0].strip()
    return None

x = 5
variable_name = get_variable_name(x)
print(variable_name)

Output:

x

In the above program, we have used the traceback.format_stack() function to get the call stack as a list of strings. We are using a for loop to iterate through the list of strings. We are checking if the line contains the variable. If yes, we are splitting the line using the equal sign and getting the first part of the line which contains the variable name. We are stripping the variable name to remove any extra spaces. We are also checking if the line contains the string "in <module>" which indicates that we have reached the top of the call stack. If we reached the call stack's top and could not find the variable, we are returning None. In the main program, we have defined a variable x and called the get_variable_name function to get its name as a string. Finally, we are printing the variable name.

Method 4: Using f-strings.

Starting from Python 3.8, f-strings allow us to access the variable name directly. Here is the program:

x = 5
variable_name = f"{x=}".split("=")[0]
print(variable_name)

Output:

x

In the above program, we have defined a variable x and used the f-string to get the variable name. We are splitting the f-string using the equal sign and getting the first part of the string which contains the variable name. We are printing the variable name.

Conclusion:

In this blog, we have discussed multiple ways to get the variable name as a string in Python. We have used the globals() and locals() functions, the inspect module, the traceback module, and f-strings. Depending on the requirement, we can choose the appropriate method. These methods can be used to debug or to use the variable name in a string message.

Comments (0)

There are no comments. Be the first to comment!!!