Home > Software design >  How to extract variable name (as an element from a list of variables) and convert it into a string?
How to extract variable name (as an element from a list of variables) and convert it into a string?

Time:06-10

nameof() can be used to print the name of a variable as a string, instead of its value itself:

from varname import nameof
var = 'Hello!'
print (nameof(var))
#Output:
var

The reason why I need this is because I want to print the value of each element of a list as it's being looped through:

from varname import nameof

green = 3
blue = 6
black = 9
white = 1
purple = 8

list_colors = [green, blue, black, white, purple]

for color in list_colors:
    print("The color being looked at is:", nameof(color))

The output I get is:

The color being looked at is: color
The color being looked at is: color
The color being looked at is: color
The color being looked at is: color
The color being looked at is: color

But rather, I need the following as the output (and also NOT the numeric values stored in each of the variables):

The color being looked at is: green
The color being looked at is: blue
The color being looked at is: black
The color being looked at is: white
The color being looked at is: purple

Can anyone please help me with this?

CodePudding user response:

If you want to do it that way, I found this from:

Getting the name of variables in a list

for i in range(len(list_colors)):
print([k for k,v in globals().items() if id(v) == id(list_colors[i])][0])

I have no idea how it works and I would do it with a 2D array (which is definitely not the best solution either), but here you go.

CodePudding user response:

Using retrieve_name by juan Isaza from Getting the name of a variable as a string

import inspect

def retrieve_name(var):
    """
    Gets the name of var. Does it from the out most frame inner-wards.
    :param var: variable to get name from.
    :return: string
    """
    for fi in reversed(inspect.stack()):
        names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]
        if len(names) > 0:
            return names[0]

green = 3
blue = 6
black = 9
white = 1
purple = 8

list_colors = [green, blue, black, white, purple]

for color in list_colors:
    print("The color being looked at is:", retrieve_name(color))

Output:

The color being looked at is: green
The color being looked at is: blue
The color being looked at is: black
The color being looked at is: white
The color being looked at is: purple
  • Related