Get Variable Name As String In Python
Last Updated :
30 Jan, 2024
In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods to obtain the variable name as a string in Python.
Get Variable Name As String In Python
Below, are the example of Get Variable Name As String In Python.
- Using locals() Function
- Using globals() Function
- Using a custom class
- Using inspect Module
Get Variable Name As String Using locals() Function
In this example, the below code defines a function, `get_var_name`, that returns the name of a local variable given its value using the `locals()` dictionary. The example demonstrates using the function to find and print the name of a variable (`my_variable`) along with its type.
Python3
def get_var_name(var):
for name, value in locals().items():
if value is var:
return name
# Example usage:
my_variable = 42
variable_name = get_var_name(my_variable)
print(f"The variable name is: {variable_name}")
print(type(variable_name))
OutputThe variable name is: var
<class 'str'>
Get Variable Name As String Using globals() Function
In this example, below code defines a function, `get_var_name`, which retrieves the name of a global variable given its value from the global namespace using `globals()`. The example demonstrates using this function to find and print the name of a variable (`my_variable`) along with its type.
Python3
def get_var_name(var):
for name, value in globals().items():
if value is var:
return name
# Example usage:
my_variable = 42
variable_name = get_var_name(my_variable)
print(f"The variable name is: {variable_name}")
print(type(variable_name))
OutputThe variable name is: my_variable
<class 'str'>
Get Variable Name As String Using a Custom Class
In this example, code defines a class `VariableWrapper` with attributes `value` and `name`. An instance of this class, `my_variable`, is created with a value of 42 and a name of "my_variable." The example then prints the name attribute of `my_variable` along with its type.
Python3
class VariableWrapper:
def __init__(self, value, name):
self.value = value
self.name = name
# Example usage:
my_variable = VariableWrapper(42, "my_variable")
print(f"The variable name is: {my_variable.name}")
print(type(my_variable.name))
OutputThe variable name is: my_variable
<class 'str'>
Get Variable Name As String Using inspect Module
In this example, below code defines a function, `get_var_name`, which uses the inspect module to obtain the name of a variable given its value. The example demonstrates using this function to find and print the name of a variable (`my_variable`) along with its type.
Python3
import inspect
def get_var_name(var):
current_frame = inspect.currentframe()
caller_frame = inspect.getouterframes(current_frame)[1]
local_vars = caller_frame.frame.f_locals
for name, value in local_vars.items():
if value is var:
return name
# Example usage:
my_variable = 42
variable_name = get_var_name(my_variable)
print(f"The variable name is: {variable_name}")
print(type(variable_name))
OutputThe variable name is: my_variable
<class 'str'>
Similar Reads
Convert String into Variable Name in Python There may be situations where you want to convert a string into a variable name dynamically. In this article, we'll explore how to convert a string into a variable name in Python with four simple examples. Convert String into Variable Name in PythonWhile Python does not directly allow you to convert
3 min read
How to get a variable name as a string in PHP? Use variable name as a string to get the variable name. There are many ways to solve this problem some of them are discussed below: Table of ContentUsing $GLOBALSUsing $$ OperatorUsing debug_backtrace()Using get_defined_vars() and array_search()Method 1: Using $GLOBALS: It is used to reference all v
3 min read
How To Print A Variable's Name In Python In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simp
3 min read
Get OS name and version in Python Python programming has several modules that can be used to retrieve information about the current operating system and the version that is running on the system. In this article we will explore How to get the OS name and version in Python.Let us see a simple example to get the OS name and version in
2 min read
Undefined Variable Nameerror In Python Encountering the "NameError: name 'var' is not defined" is a common experience for Python users. In Python, variable declaration is a straightforward process of assigning a value. This error arises when attempting to access a non-existent variable or one not defined in the program. Surprisingly, it
5 min read
Convert string to title case in Python In this article, we will see how to convert the string to a title case in Python. The str.title() method capitalizes the first letter of every word.Pythons = "geeks for geeks" result = s.title() print(result) OutputGeeks For Geeks Explanation:The s.title() method converts the string "python is fun"
2 min read
Get tag name using Beautifulsoup in Python Prerequisite: Beautifulsoup Installation Name property is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. Name object corresponds to the name of an XML or HTML t
1 min read
What does %s mean in a Python format string? In Python, the %s format specifier is used to represent a placeholder for a string in a string formatting operation. It allows us to insert values dynamically into a string, making our code more flexible and readable. This placeholder is part of Python's older string formatting method, using the % o
3 min read
Call a function by a String name - Python In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between
3 min read
Python String Title method title() method in Python is a simple way to convert a string to a title case, where the first letter of each word is capitalized and all other letters are lowercase. Let's understand with the help of an example:Pythona = "hello geek" # Converts string to title case b = a.title() print(b)OutputHello
2 min read