0

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 
2
  • 4
    There is exactly one empty string object in your script, with five names referring to it. Any one of those names has exactly equal claim to being the name of the empty string; it's pure coincidence that i happened to be the name that was shown. The whole concept of nameof() is flawed; it simply does not reflect how Python actually works. Commented Sep 24, 2022 at 22:15
  • 5
    @jasonharper it frightens me that anyone even attempted to create a library such as the one being asked about. Commented Sep 24, 2022 at 22:17

3 Answers 3

3

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': ''} 
Sign up to request clarification or add additional context in comments.

Comments

2

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 

Comments

-1

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.

1 Comment

is this an answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.