0

I would like to know if it's possible to get the name of the variable who call the function, and how. For example :

myVar = something
myVar2 = something
myVar.function()
myVar2.function()

and the code should return

myVar calls function()
myVar2 calls function()

Thank you.

Guillaume
  • 8,741
  • 11
  • 49
  • 62
  • 1
    You might wanna take a look at this: http://stackoverflow.com/questions/1534504/convert-variable-name-to-string since this is possible copy of it. –  Nov 25 '12 at 19:07

4 Answers4

3

It seems like something is an object of a custom class already (if this is a built-in class, you can subclass it). Just add an instance attribute name, assign it when creating and use later:

In [1]: class MyClass:
   ...:     def __init__(self, name):
   ...:         self.name = name
   ...:     def function(self):
   ...:         print 'function called on', self.name
   ...: 

In [2]: myVar = MyClass('Joe')

In [3]: myVar2 = MyClass('Ben')

In [4]: myVar.function()
function called on Joe

In [5]: myVar2.function()
function called on Ben

P.S. I know this is not exactly what you are asking, but I think this is better than actually trying to use the variable name. The question mentioned in the comment above has a very nice answer explaining why.

Community
  • 1
  • 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
1

There might not be a name:

def another:
    return something 

another().function()

Lev's answer has the nice property that it does not depend on any internal python implementation details. Lev's technique is the one I usually use.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
GeePokey
  • 159
  • 7
1

You can make some stack manipulation to achieve that, but I certainly do not recommend doing it. Hope you never use it in real code:

>>> class C:
        def function(self):
            text = inspect.stack()[1][4][0].strip().split('.')
            return '{0} calls {1}'.format(*text)

>>> myVar = C()
>>> myVar.function()
'myVar calls function()'
JBernardo
  • 32,262
  • 10
  • 90
  • 115
0

You can do:

def myfuncname():
    pass
myvar=myfuncname
print globals()['myvar'].__name__

and it will print the name of the function the variable is assigned to.

IT Ninja
  • 6,174
  • 10
  • 42
  • 65
  • 1
    What?!? `globals()['myvar']` is, barring shadowing by a local variable (which is not the case here), equal to just referencing `myvar`. Second, the `__name__` of a function is the name used during its definition (if it's not changed manually later on), so this will print `myfuncname`, not `myvar`, even if the variable `myfuncname` no longer exists or refers to something different. Third, this is not what the question asks for. -1 –  Nov 25 '12 at 19:13