0

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?

EnigmAI
  • 157
  • 1
  • 9
  • 1
    Why don't you make your list of colors into a dictionary? – jonsca Jun 09 '22 at 07:08
  • 3
    Don't do it that way. Set up dictionary `color = {"green": 3, "blue": 6, ...}` and then do `for c in color.keys(): print (c)`. – BoarGules Jun 09 '22 at 07:09
  • @BoarGules ok, this seems to be a good approach. But only thing, my variables are actually more complicated. As in, each variable is something like "package.function(arg1, arg2)". So even in this case would it work? – EnigmAI Jun 09 '22 at 07:18
  • I don't understand what you mean by *each variable*. Do you expect to print a string showing the name of the package and function? Or the value returned by the function? – BoarGules Jun 09 '22 at 07:27
  • @BoarGules what I mean is that my variables of green, blue, etc. are not just plain numeric values. Instead of the individual numbers I've assigned here, in reality it's something like this: e.g.: blue = somepackage.function(arg1, arg2). Similarly for other colors. My objective is the same only that I've illustrated, i.e. print the colors as the output, and not their values. So would using a dictionary work in this case too? – EnigmAI Jun 09 '22 at 12:52
  • Yes. It would. You can put computed values in a `dict`, both as values and as keys. Though the keys have to be expressions that resolve to strings or numbers or something else immutable like a tuple (and, with tuples, so on downwards). – BoarGules Jun 09 '22 at 13:29
  • @BoarGules It doesn't seem to work. The following is the issue - when I define the key like e.g. 'blue' = somepackage.function(arg1, arg2), there are multiple return values coming from the function somepackage.function(). Had the assignment of 'blue' not been made as a string (which I've to do here since it's a dictionary key), but instead as a simple variable in a list, writing blue.return1, blue.return2, etc. helps me access the return values. But here I'm not able to do so. So how do I access these return values? – EnigmAI Jun 10 '22 at 13:59

2 Answers2

0

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.

Tmate
  • 1
  • 1
  • 1
    Don't do it that way either. It only works by accident, as you will find out if you do it in a real program. – BoarGules Jun 09 '22 at 07:21
0

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
GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16
  • 1
    Very clever. But *please* don't encourage beginners to do this sort of thing. When the obvious solution is to use a `list` or a `dict`, they should not be encouraged to use techniques that would attract very unsympathetic comments from their peers in a code review. – BoarGules Jun 09 '22 at 13:36
  • Yeah fair enough. It doesn't even work for _EnigmAI_'s use case, as the list would have elements like `package.function(arg1, arg2)`. I'd be interested to know if you could retrieve that full expression at runtime, after the list has been created. – GordonAitchJay Jun 10 '22 at 10:38