how to use python varname to get var names inside loops

Viewed 43

I'm using the fantastic varname python package https://pypi.org/project/varname/ to print python var names from inside the code:

    >>> from varname import nameof
    >>> myvar = 42
    >>> print(f'{nameof(myvar)} + 8: {myvar + 8}')
    myvar + 8: 50
    >>>

but when I try to use it in a loop:

    >>> a, b, c, d = '', '', '', ''
    >>> for i in (a, b, c, d):
        print(f'{nameof(i)}') 
    i
    i
    i
    i
    >>>

I do not get to print a, b, c, ...

How could I get something like this ?:

a 
b
c
d
3 Answers

You need to use Wrapper, to see varname in a loop then.

from varname.helpers import Wrapper

a = Wrapper('')
b = Wrapper('')
c = Wrapper('')
d = Wrapper('')


def values_to_dict(*args):
    return {val.name: val.value for val in args}


mydict = values_to_dict(a, b, c, d)
print(mydict)
# {'a': '', 'b': '', 'c': '', 'd': ''}

Well, I've never used nameof(), but in your loop, it's always going to return i, because that's what you've asked for with for i in (a,b,c,d): All that is doing, is to iterate over the tuple, assigning each element of the tuple to i, then printing the 'name', which is, logically, always going to be i.

You can put the for loop into a function, and then use argname:

from varname import argname
a, b, c, d = '1', '2', '3', '4'
def fun(*args):
    names = argname('args')
    for i, name_of_i in zip(args, names):
        print(f'Variable name: {name_of_i}  Value: {i}')

Output of fun(a,b,c,d):

Variable name: a  Value: 1
Variable name: b  Value: 2
Variable name: c  Value: 3
Variable name: d  Value: 4
Related