Python: how to get the class of the calling method through validation?

For my exception class, I would like to know if the function that created the exception object instance is a method, and if so, show the class name.

So, in the init method of my exception class, I get the name of the calling function:

frame, module, line, function, context, index = inspect.stack()[1]

But is there a way to get the class name (if any) of the calling function?

+3
source share
1 answer

Assuming the frame is for an instance method:

self_argument = frame.f_code.co_varnames[0]  # This *should* be 'self'.
instance = frame.f_locals[self_argument]
class_name = instance.__class__.__name__
+2
source

All Articles