
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Variable Name as String in Python
In Python Variables are just the labels that are pointing to the values. They don't carry any built-in metadata about their names. That's why there is no direct built-in method to get the variable name as a string.
However, we can achieve this, by inspecting the environment such as using the globals(), locals(), or the inspect module. Let's dive into the article to learn more about getting a variable name as a string.
Using Python globals() Function
The Python globals() function is used to return a dictionary representing the current global symbol table. It provides the access to all the global variables and their corresponding values in the current scope. With the help of this feature, we can retrieve, modify or delete global variables.
Syntax
Following is the syntax for Python globals() function -
globals()
Example
Let's look at the following example, where we are going to consider the basic usage of the globals() function.
demo = 12345 result = [name for name, val in globals().items() if val is demo][0] print(f"The variable is : {result}")
Output
Output of the above program is as follows -
The variable is : demo
Using Python locals() Function
The Python locals() function is a built-in function that returns the dictionary representing the current local symbol table. It provide access to all the local variables, functions and their corresponding values.
Syntax
Following is the syntax for Python locals() function -
locals()
Example
In the following example, where we are going to consider the 2variables, and finding out the variable names.
math = 75 chem = 69 variable = [] variable.append([ i for i, j in locals().items() if j == math][0]) variable.append([ i for i, j in locals().items() if j == chem][0]) print("The variable names are") print(variable)
Output
Output of the above program is as follows -
The variable names are ['math', 'chem']
Using Python inspect Module
The Python inspect module is the part of the standard library and provides the tools to observe the type or properties of object in runtime. It allows to retrieve the information about live objects such as functions, classes.
Example
Consider the following example, Where we are going to use inspect module and getting the local variable name.
import inspect def x(var): y = inspect.currentframe().f_back return [name for name, val in y.f_locals.items() if val is var][0] def tp(): demo = "Welcome" print(x(demo)) tp()
Output
Following is the output of the above program -
demo