get fully qualified method name from inspect stack

2024/9/8 8:39:36

I have trouble completing the following function:

def fullyQualifiedMethodNameInStack(depth=1):"""The function should return <file>_<class>_<method> for the method in the stack at specified depth."""fileName=inspect.stack()[depth][1]methodName=inspect.stack()[depth][3]class= """ please help!!! """baseName=os.path.splitext( os.path.basename( fileName ) )[0]return '{0}_{1}_{2}'.format( baseName, className, methodName )

As you can see I want the class name of the method being executed. The stack that inspect returns only has the method name, and I do not know how to find the class belonging to the method.

Answer

You are always looking at a function context; the method context is already gone by the time the function executes. Technically speaking, functions act as descriptors when accessed as attributes on an instance (instance.method_name), which return a method object. The method object then, when called, in turn calls the original function with the instance as the first argument. Because this all happens in C code, no trace of the original method object remains on the Python stack.

The stack only needs to keep track of namespaces and the code to be executed for the local namespace. The original function object is no longer needed for these functions, only the attached code object still retains the name of the original function definition for traceback purposes.

If you know the function to be a method, you could search for a self local name. If present, type(self) is the class of the instance, which is not necessarily the class the method was defined on.

You would then have to search the class and it's bases (looping over the .__mro__ attribute) to try and locate what class defined that method.

There are a few more snags you need to take into account:

  • Naming the first argument of a method self is only a convention. If someone picked a different name, you won't be able to figure that out without parsing the Python source yourself, or by going up another step in the stack and trying to deduce from that line how the function was called, then retrieve the method and it's .im_self attribute.

  • You only are given the original name of the function, under which it was defined. That is not necessarily the name under which it was invoked. Functions are first-class objects and can be added to classes under different names.

  • Although a function was passed in self and was defined as part of a class definition, it could have been invoked by manually passing in a value for self instead of the usual route of the method (being the result of the function acting as a descriptor) passing in the self reference for the caller.

In Python 3.3 and up, the situation is marginally better; function objects have a new __qualname__ attribute, which would include the class name. The problem is then that you still need to locate the function object from the parent stack frame.

https://en.xdnf.cn/q/73276.html

Related Q&A

Project Euler #18 - how to brute force all possible paths in tree-like structure using Python?

Am trying to learn Python the Atlantic way and am stuck on Project Euler #18.All of the stuff I can find on the web (and theres a LOT more googling that happened beyond that) is some variation on well …

Is it possible to sniff the Character encoding?

I have a webpage that accepts CSV files. These files may be created in a variety of places. (I think) there is no way to specify the encoding in a CSV file - so I can not reliably treat all of them as …

numpy.empty giving nonempty array

When I create an empty numpy array using foo = np.empty(1) the resulting array contains a float64:>>> foo = np.empty(1) >>> foo array([ 0.]) >>> type(foo[0]) <type numpy.f…

Accessing password protected url from python script

In python, I want to send a request to a url which will return some information to me. The problem is if I try to access the url from the browser, a popup box appears and asks for a username and passwo…

Solving multiple linear sparse matrix equations: numpy.linalg.solve vs. scipy.sparse.linalg.spsolve

I have to solve a large amount of linear matrix equations of the type "Ax=B" for x where A is a sparse matrix with mainly the main diagonal populated and B is a vector. My first approach was …

I want to return html in a flask route [duplicate]

This question already has answers here:Python Flask Render Text from Variable like render_template(4 answers)Closed 6 years ago.Instead of using send_static_file, I want to use something like html(<…

Why doesnt cv2 dilate actually affect my image?

So, Im generating a binary (well, really gray scale, 8bit, used as binary) image with python and opencv2, writing a small number of polygons to the image, and then dilating the image using a kernel. Ho…

How to plot text clusters?

I have started to learn clustering with Python and sklearn library. I have wrote a simple code for clustering text data. My goal is to find groups / clusters of similar sentences. I have tried to plot…

Selenium - Unresponsive Script Error (Firefox)

This question has been asked before, but the answer given does not seem to work for me. The problem is, when opening a page using Selenium, I get numerous "Unresponsive Script" pop ups, refe…

Fail to validate URL in Facebook webhook subscription with python flask on the back end and ssl

Im trying to start using new messenger platform from FB. So i have server with name (i.e.) www.mysite.com I got a valid SSL certificate for that domain and apache is setup correctly - all good.I have …