![]() |
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 PythonBelow, are the example of Get Variable Name As String In Python.
Get Variable Name As String Using locals() FunctionIn 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
Output
The variable name is: var <class 'str'> Get Variable Name As String Using globals() FunctionIn 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
Output
The variable name is: my_variable <class 'str'> Get Variable Name As String Using a Custom ClassIn 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
Output
The variable name is: my_variable <class 'str'> Get Variable Name As String Using inspect ModuleIn 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
Output
The variable name is: my_variable <class 'str'> |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |