Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How to get python caller object information?

How can I fetch the caller object from within a function, and inspect information about that caller?

class A(object):
 def class_A_fun(self):
 print 'caller from class' # → B
 print 'caller from method' # → class_B_fun
 print 'caller module' # → foomodule
 print 'caller instance' # → obj
 print 'caller object file name or path' # → 'foomodule.py'
class B(object):
 def class_B_fun(self): 
 obj = A()
 obj.class_A_fun() 
if __name__ == "__main__":
 obj = B()
 obj.class_B_fun()

Answer*

Draft saved
Draft discarded
Cancel
2
  • there is nothing that says your caller must have a local called self. that's pure convention (for methods not functions) Commented Sep 2, 2022 at 11:25
  • 1
    @DavidJones I changed my answer, however there are more complicated situations, e.g. for a static method. In the end one may need to analyze the whole source code to properly identify the calling object. Commented Sep 7, 2022 at 15:18

lang-py

AltStyle によって変換されたページ (->オリジナル) /