Python how to get the calling function (not just its name)?

Calling can happen from any code object (and from an extension module/builtin): from exec, execfile, from module name space (during import), from within a class definition, from within a method / classmethod / staticmethod, from a decorated function/method, from within a nested function, … – so there is no “calling function” in general, and the … Read more

How to get all methods of a Python class with given decorator?

Method 1: Basic registering decorator I already answered this question here: Calling functions by array index in Python =) Method 2: Sourcecode parsing If you do not have control over the class definition, which is one interpretation of what you’d like to suppose, this is impossible (without code-reading-reflection), since for example the decorator could be … Read more

Using a dictionary to select function to execute

Simplify, simplify, simplify: def p1(args): whatever def p2(more args): whatever myDict = { “P1”: p1, “P2”: p2, … “Pn”: pn } def myMain(name): myDict[name]() That’s all you need. You might consider the use of dict.get with a callable default if name refers to an invalid function— def myMain(name): myDict.get(name, lambda: ‘Invalid’)() (Picked this neat trick … Read more

How to use inspect to get the caller’s info from callee in Python?

The caller’s frame is one frame higher than the current frame. You can use inspect.currentframe().f_back to find the caller’s frame. Then use inspect.getframeinfo to get the caller’s filename and line number. import inspect def hello(): previous_frame = inspect.currentframe().f_back (filename, line_number, function_name, lines, index) = inspect.getframeinfo(previous_frame) return (filename, line_number, function_name, lines, index) print(hello()) # (‘/home/unutbu/pybin/test.py’, 10, … Read more