0

In python3, I would like to do the following simple thing: given any variable, get its name as a string. That is, I would like some function, such that when the following code is run:

a = 0
b = a.someFunction()
print(b)

The output is:

'a'

Does python3 have this capability?

martineau
  • 119,623
  • 25
  • 170
  • 301
splinter
  • 3,727
  • 8
  • 37
  • 82
  • 1
    You're essentially asking "what is the name of 0." This doesn't really have a good answer. It's technically possible to dig out a name by using some Python voodoo, but a value may have many names in many scopes and most of them will not be particularly useful. Suppose you write `c = [a]`. Now `c[0]` is a name for `0`. – kindall Jan 11 '17 at 23:29

1 Answers1

1

If I understand you correctly, you don't care about the value of the variable itself, you care about getting it's NAME as a string, storing it, and passing it around. Most people who need to do stuff like that don't need to for primitives like integers (since you already know the name, you just wrote it), but they store the keys of hashes (python dictionaries). consider using python dictionaries, and key's for the larger solution.

Jon Malachowski
  • 256
  • 1
  • 7
  • You are right, I want the NAME as a string. Is there no simple pythonic way to acheive this? – splinter Jan 11 '17 at 23:26
  • `a = b = c = d = e = 0`. Now you want a magic function that will take `0` and get a name for it. Which name do you want? – kindall Jan 11 '17 at 23:45