Is it possible to retrieve any class information from a frame object? I know how to get the file (frame.f_code.co_filename), function (frame.f_code.co_name) and line number (frame.f_lineno), but would like to be able to also get the name of the class of the active object instance of the frame (or None if not in an instance).
Share
I don’t believe that, at the frame object level, there’s any way to find the actual python function object that has been called.
However, if your code rely on the common convention : naming the instance parameter of a method
self, then you could do the following :If you don’t want to use
getargvalues, you can use directlyframe.f_localsinstead ofvalue_dictandframe.f_code.co_varnames[:frame.f_code.co_argcount]instead ofargs.Keep in mind that this is still only relying on convention, so it is not portable, and error-prone:
selfas first parameter name, thenget_class_from_framewill wrongly return the class of the first parameter.@classmethodand@staticmethodwon’t take aselfparameter and are implemented with descriptors.Depending on what exactly you want to do, you might want to take some time to dig deeper and find workarounds for all these issues (you could check the frame function exist in the returned class and share the same source, detecting descriptor calls is possible, same for class methods, etc..)