Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
How to get method name in python?

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.

You can use inspect module to do exactly this job:
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
caller_method = calframe[0][3]
The part that you are interested in, is calframe[0][3]. It returns function name of the current method. If this method is called from a parent method (caller method), you have to get that method name using calframe[1][3].

A sample code for the inspect module:
import inspect


class PDFtoJPG:
def _internal_conversion(self):
self.convert_to_jpg()

def convert_to_jpg(self):
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
print calframe[0][3]
print calframe[1][3]
print calframe[2][3]

def convert(self):
self._internal_conversion()


snd = PDFtoJPG()
snd.convert()
#python #inspect #calframe #method_name