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.

1
  • 1
    You might wanna take a look at this: stackoverflow.com/questions/1534504/… since this is possible copy of it. Commented Nov 25, 2012 at 19:07

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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()' 

Comments

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.

Comments

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.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.