I am programmatically printing out a list of function in python. I can get the name from name
for ifunc,func in enumerate(list_of_functions):
print(str(ifunc)+func.__name__)
How to get the source filename where the function is defined as well?
and in case the function it is attribute of a object, how to get the type of parent object?
portability python2/3 is a must
In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.
Functions can be defined inside a module, a class, or another function. Function defined inside a class is called a method. In this example, we define an f function in three different places. A static method is defined with a decorator in a Some class.
The open() function is used in Python to open a file. Using the open() function is one way to check a particular file is opened or closed. If the open() function opens a previously opened file, then an IOError will be generated.
All functions must be defined before any are used. However, the functions can be defined in any order, as long as all are defined before any executable code uses a function.
func.__module__
Will return the module in witch it is defined
func.__globals__['__file__']
will return the whole path of the file where it is defined.Only for user defined functions
How to get the source filename where the function is defined ... ?
import inspect
inspect.getfile(func)
and in case the function it is attribute of a object, how to get the type of parent object?
To get the class of a method (i.e. when the function is an attribute of a object):
if inspect.ismethod(func):
the_class = func.__self__.__class__
ref: https://docs.python.org/3/library/inspect.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With