Skip to content
Advertisement

Get the object that a function was called from in python

If I have a class that contains a method, and I call that method from an instance, how do I get the specific instance it was called from?

e.g. I have a class:

class foo:
   def __init__(self):
      pass
   def do_something(self):
      bar()

I also have a function:

def bar():
   print()

If i make an object, e.g. obj = foo(), and then i call obj.do_something(), How would i get obj from inside my bar() function?

Advertisement

Answer

Using the inspect module, you can get the caller frame and access its local variables, in particular the self argument representing the instance:

import inspect


def bar():
    caller = inspect.stack()[1].frame
    localvars = caller.f_locals
    self = localvars['self']
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement