2

I'd like to be able to access the name of a variable that is passed to a function as e.g.

def f(x):
    '''Returns name of list/dict variable passed to f'''
    return magic(x)

>>a = [1,2,3]
>>print( f(a) )
'a'
>>print( f(2) )
None

I suspect this is possible using Python introspection but I don't know enough to understand the inspect module. (NB I know that the need for a function like magic() is questionable, but it is what I want.)

ham-sandwich
  • 3,975
  • 10
  • 34
  • 46
user1476044
  • 281
  • 1
  • 4
  • 13
  • *"but it is what I want"* - why? What are you actually trying to **achieve** with this? And why did I have to Google that for you? – jonrsharpe Nov 04 '15 at 14:50
  • Now that I see that this is a duplicate question, I'm reversing my upvote of the question to a downvote. – rmunn Nov 04 '15 at 14:56

1 Answers1

0

Actually, this is not possible. In Python names and values are quite separate. Inside f, you have access to the value of x, but it is not possible to find out what other names other functions might have given to that value.

Think of names as being somewhat like pointers in C. If you have a pointer, you can find out what object it points to. But if you have the object, you cannot find out what pointers are pointing to it.

rmunn
  • 34,942
  • 10
  • 74
  • 105