Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the path of a function in Python?

Tags:

python

I want to obtain the file path of a function in Python.

How to do it?

For example,

import keras.backend as K
y = K.resize_images(x, 2, 2, 'channels_last')
path = function(K.resize_images)
print(path)
#C:\Program Files\Python36\Lib\site-packages\keras\backend\tensorflow_backend.py

Thank you.

like image 581
John Avatar asked Jun 04 '18 04:06

John


People also ask

What is path () in Python?

PYTHONPATH is an environment variable which the user can set to add additional directories that the user wants Python to add to the sys. path directory list. In short, we can say that it is an environment variable that you set before running the Python interpreter.

How do I get the path of a Python file executed?

Run it with the python (or python3 ) command. You can get the absolute path of the current working directory with os. getcwd() and the path specified with the python3 command with __file__ . In Python 3.8 and earlier, the path specified by the python (or python3 ) command is stored in __file__ .

How do I get the full path of a file in Python?

To get current file's full path, you can use the os. path. abspath function. If you want only the directory path, you can call os.


2 Answers

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
like image 60
chuckx Avatar answered Oct 21 '22 18:10

chuckx


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") 
like image 42
juancarlos Avatar answered Oct 21 '22 19:10

juancarlos