Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get a variable name as a string in Python?
In Python, variables are just labels pointing to values. They don't carry any built-in metadata about their names, so there's no direct method to get a variable name as a string.
However, we can achieve this by inspecting the environment using globals(), locals(), or the inspect module. Let's explore these approaches ?
Using globals() Function
The globals() function returns a dictionary representing the current global symbol table. We can search through this dictionary to find variable names by their values.
Syntax
globals()
Example
Here's how to find a global variable name using its value ?
demo = 12345
result = [name for name, val in globals().items() if val is demo][0]
print(f"The variable name is: {result}")
The variable name is: demo
Using locals() Function
The locals() function returns a dictionary representing the current local symbol table. This works within function scope to find local variable names.
Syntax
locals()
Example
In this example, we find names of multiple local variables ?
def find_variable_names():
math = 75
chemistry = 69
variable_names = []
variable_names.append([name for name, val in locals().items() if val == math][0])
variable_names.append([name for name, val in locals().items() if val == chemistry][0])
print("The variable names are:")
print(variable_names)
find_variable_names()
The variable names are: ['math', 'chemistry']
Using inspect Module
The inspect module provides tools to examine live objects at runtime. It can access frame information to retrieve variable names from calling functions.
Example
Here's how to get a variable name from the calling function ?
import inspect
def get_variable_name(var):
frame = inspect.currentframe().f_back
return [name for name, val in frame.f_locals.items() if val is var][0]
def test_function():
welcome_message = "Welcome to TutorialsPoint"
print(f"Variable name: {get_variable_name(welcome_message)}")
test_function()
Variable name: welcome_message
Comparison of Methods
| Method | Scope | Best For |
|---|---|---|
globals() |
Global variables | Module-level variables |
locals() |
Local variables | Function-level variables |
inspect |
Cross-function | Getting names from calling functions |
Conclusion
While Python doesn't provide direct variable name access, globals(), locals(), and the inspect module offer workarounds. Use these methods sparingly as they can make code harder to maintain and debug.
