Guillaume
Guillaume

Reputation: 9061

Get the name of a variable

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.

Upvotes: 0

Views: 272

Answers (4)

JBernardo
JBernardo

Reputation: 33397

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

Upvotes: 1

GeePokey
GeePokey

Reputation: 168

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.

Upvotes: 1

Lev Levitsky
Lev Levitsky

Reputation: 65791

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.

Upvotes: 3

IT Ninja
IT Ninja

Reputation: 6430

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.

Upvotes: 0

Related Questions