Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the name of a variable as a string

I already read How to get a function name as a string?.

How can I do the same for a variable? As opposed to functions, Python variables do not have the __name__ attribute.

In other words, if I have a variable such as:

foo = dict()
foo['bar'] = 2

I am looking for a function/attribute, e.g. retrieve_name() in order to create a DataFrame in Pandas from this list, where the column names are given by the names of the actual dictionaries:

# List of dictionaries for my DataFrame
list_of_dicts = [n_jobs, users, queues, priorities]
columns = [retrieve_name(d) for d in list_of_dicts] 
like image 586
Amelio Vazquez-Reina Avatar asked Sep 26 '22 17:09

Amelio Vazquez-Reina


People also ask

How do I find the string name of a variable?

We can access the variable names in python using the globals() function and the locals() function. The globals() function, when executed, returns a dictionary that contains all the variable names as string literals and their corresponding values.

How do I turn a variable into a string?

Converting Numbers to Strings We can convert numbers to strings through using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.

Is a variable name a string?

A string variable is a variable that holds a character string. It is a section of memory that has been given a name by the programmer. The name looks like those variable names you have seen so far, except that the name of a string variable ends with a dollar sign, $. The $ is part of the name.

How do you print a variable name as a string in Python?

The locals() function is then utilized to get the details of the given local table in the form of a Python dictionary . Finally, within the locals() function, we will use the items() or the iteritems() function depending on the compiler version to receive and print the name of the variable as a string in the output.


2 Answers

With Python 3.8 one can simply use f-string debugging feature:

>>> foo = dict()
>>> f'{foo=}'.split('=')[0]
'foo' 

One drawback of this method is that in order to get 'foo' printed you have to add f'{foo=}' yourself. In other words, you already have to know the name of the variable. In other words, the above code snippet is exactly the same as just

>>> 'foo'

Please see the other answers here that might be applicable to answer the question.

like image 236
Aivar Paalberg Avatar answered Oct 13 '22 22:10

Aivar Paalberg


Even if variable values don't point back to the name, you have access to the list of every assigned variable and its value, so I'm astounded that only one person suggested looping through there to look for your var name.

Someone mentioned on that answer that you might have to walk the stack and check everyone's locals and globals to find foo, but if foo is assigned in the scope where you're calling this retrieve_name function, you can use inspect's current frame to get you all of those local variables.

My explanation might be a little bit too wordy (maybe I should've used a "foo" less words), but here's how it would look in code (Note that if there is more than one variable assigned to the same value, you will get both of those variable names):

import inspect

x, y, z = 1, 2, 3

def retrieve_name(var):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]

print(retrieve_name(y))

If you're calling this function from another function, something like:

def foo(bar):
    return retrieve_name(bar)

foo(baz)

And you want the baz instead of bar, you'll just need to go back a scope further. This can be done by adding an extra .f_back in the caller_local_vars initialization.

See an example here: ideone

like image 141
scohe001 Avatar answered Oct 14 '22 00:10

scohe001