How to get the path of a function in Python?

You can use the getfile() function from the inspect module for this purpose.

For example, given the following files:

inspect-example.py

#!/usr/bin/python

import os
import inspect
import external_def

def foo():
  pass
    
print(os.path.abspath(inspect.getfile(foo)))
print(os.path.abspath(inspect.getfile(external_def.bar)))

external_def.py

def bar():
  pass

Executing inspect_example.py produces the following output:

$ python inspect-example.py
/home/chuckx/code/stackoverflow/inspect-example.py
/home/chuckx/code/stackoverflow/external_def.py

if you want to obtain the path of the file that contains a function you can try the following code, note: this code only works if the object type is 'function'

def get_path(func):  
     if type(func).__name__ == 'function' : 
         return func.__code__.co_filename
     else: 
         raise ValueError("'func' must be a function") 

Tags:

Python