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).
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
This is a bit shorter, but does about the same. Returns None if class name not available.
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_locals
instead ofvalue_dict
andframe.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:
self
as first parameter name, thenget_class_from_frame
will wrongly return the class of the first parameter.@classmethod
and@staticmethod
won't take aself
parameter 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..)
I just came across this post as I was faced with the same problem. I did not consider the 'self' method an acceptable solution, however, for all the reasons already listed.
The following code demonstrates a different approach: given a frame object it searches the globals for an object with matching member name and code block. The search is hardly exhaustive so it is possible that not all classes will be uncovered, but what classes are found should be the ones we are looking for because we verify matching codes.
Object of the code is to prepend a function name with its class name, if found:
Note the use of
__dict__
instead ofgetattr
to prevent catching of derived classes.Note further that a global search can be avoided if
self = frame.f_locals['self']; obj = self.__class__
gives a match, or anyobj in self.__class__.__bases__
or deeper, so there is certainly room for optimization / hybridization.If a method is a class method, the class will be the first argument. This prints out the type of the first arg if present for each calling stack frame: