Skip to content
Advertisement

how to use python varname to get var names inside loops

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement