I know how to get a caller method name (from here: How to get the caller's method name in the called method?)
import sys
print sys._getframe().f_back.f_code.co_name
What I'd like to get is the class name this method belongs to (assuming that it is in the class).
So if:
def get_some_info():
print('Class name of caller:', XXX)
class Base:
def my_method(self):
get_some_info()
class A(Base):
pass
class B(Base):
pass
a = A()
b = B()
a.my_method()
b.my_method()
should return:
... A
... B
What should I do in xxx
?
I tried (using info on _getframe
) do something like:
sys._getframe().f_back.f_code.__self__
but it doesn't work
UPDATE:
I cannot pass class name to a called function (otherwise that would be easy, but thanks to all who suggested this solution!)
Best Answer
You can get the calling frame object with
inspect.currentframe()
and get the object thatself
is bound to through itsf_locals
attribute:The disadvantage of this is that it relies on the first parameter to be named "self". There are a few cases where we use different names, for example when writing a metaclass:
And if you have a function with a
self
variable, it can produce unexpected results:We can solve both of these problems, but it takes a lot of work. We can inspect the name of the "self" parameter through the calling code object's
co_varnames
attribute. And in order to check whether the calling function is really a method defined in a class, we can loop through theself
's MRO and try to find the method that called us. The end result is this monstrosity:This should handle pretty much everything you throw at it correctly: