Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine from which file a function is defined in python

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

like image 780
00__00__00 Avatar asked May 31 '18 08:05

00__00__00


People also ask

How do you find the path of a function in Python?

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.

Where is function defined in Python module or class?

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.

Which function is used to see the status of file in Python?

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.

Do Python functions have to be defined in order?

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.


2 Answers

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

like image 191
Smart Manoj Avatar answered Oct 23 '22 10:10

Smart Manoj


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

like image 42
JobJob Avatar answered Oct 23 '22 11:10

JobJob