15

If I have local/global variable var of any type how do I get its name, i.e. string "var"? I.e. for some imaginary function or operator nameof() next code should work:

var = 123
assert nameof(var) == "var"

There's .__name__ property for getting name of a function or a type object that variable holds value of, but is there anything like this for getting name of a variable itself?

Can this be achieved without wrapping a variable into some magic object, as some libraries do in order to get variable's name? If not possible to achieve without magic wrappers then what is the most common/popular wrapping library used for this case?

Arty
  • 14,883
  • 6
  • 36
  • 69
  • 1
    Does this answer your question? [Getting the name of a variable as a string](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) – Riccardo Bucco Oct 03 '20 at 08:11
  • 2
    There's no inherent name to data (if you do `x = SomeObject(); y = x`, then what would be the name of `SomeObject()`?) The easiest way would be to use a dict to store your data. – AKX Oct 03 '20 at 08:12
  • @AKX Any language stores all variables' (name, value) pairs in some internal table. Hence this name can be obtained somehow. In already [answer was posted](https://stackoverflow.com/a/64182128/941531) which solves my task perfectly well! – Arty Oct 03 '20 at 09:25
  • @Arty Any interpreted language, yeah. I'm glad you found a solution, but it _is_ magic I wouldn't trust to work 100% in any given situation. – AKX Oct 03 '20 at 10:24

2 Answers2

23

You can do this with the package python-varname: https://github.com/pwwang/python-varname

First run pip install varname. Then see the code below:

from varname import nameof
var = 123
name = nameof(var)
#name will be 'var'
Fried Noodles
  • 287
  • 2
  • 8
20

For Python 3.8 and later, you can try this not-so-pretty way, but it works for any python object that has a str-method:

var = 123
var_name = f'{var=}'.partition('=')[0]
Sum Zbrod
  • 301
  • 2
  • 4
  • 1
    Thanks! Seems to work. The only drawback that it seems to work only starting from Python 3.8. I just tested it now on 3.7/3.8/3.9, and only 3.8/3.9 run without error. Anyway upvoting your answer! You may also add comment to your answer that it works starting from 3.8. – Arty Sep 17 '21 at 08:14
  • 1
    Also there is a nicer (and less error-prone) way to get something before `=` sign: `var_name = f'{var=}'.partition('=')[0]` – Arty Sep 17 '21 at 08:17
  • 3
    This answer is not useful since the code uses the name of the variable, which is what you should get, not provide. You could just write `var_name = 'var'` instead of your line of code. – Georg Apr 26 '22 at 13:25
  • @Georg: ...and that case you can mistype the 'var'. The point could be to checked (by the linter) that the string contains the variably name is really a variable name and not mistyped – g.pickardou Jun 15 '22 at 05:26