hamzaahmad
hamzaahmad

Reputation: 153

Python: How to get the absolute path of file where a function was called?

In Python, the __file__ double underscore variable can be used to get the file path of the script where the variable is used. Is there way to get the file path of the script where a function was called?

The only way I've been able to do this is to pass __file__ to the function. I don't want to do this every time I use the function. Is there a different double underscore variable that I can use? Or is there a way to check the namespace for the absolute path of where the function was called?

This is what I have:

Contents of definition.py
def my_function(message, filepath_where_function_is_called):
    print(message)
    print("This function was called in:", filepath_where_function_is_called)
Contents of my_script.py
from definition import my_function

my_function(message="Hello world!", filepath_where_function_is_called=__file__)
Running my_script.py
$ python3 my_script.py
Hello world!
This function was called in: /path/to/my_script.py

This is what I want:

Contents of definition.py
def my_function(message):
    print(message)
    filepath_where_function_is_called = ...  # I don't know this piece 
    print("This function was called in:", filepath_where_function_is_called)
Contents of my_script.py
from definition import my_function

my_function(message="Hello world!")
Running my_script.py
$ python3 my_script.py
Hello world!
This function was called in: /path/to/my_script.py

Upvotes: 5

Views: 1950

Answers (1)

DYZ
DYZ

Reputation: 57033

You can use module traceback to get access to the call stack. The last element of the call stack is the most recently called function. The second last element is the caller of the most recently called function.

foo.py:

import traceback
def foo(): 
    stack = traceback.extract_stack()
    print(stack[-2].filename)

bar.py:

import foo
foo.foo()

On the prompt:

import bar
# /path/to/bar.py

Upvotes: 12

Related Questions