As wim said, the function gets executed in such a way that __file__
will return the name of the file the function is present in (File1.py).
It is however possible to achieve what you want, although again as wim said it is a bit hacky. You can do this by looking at the frame records in the call stack using inspect.stack
:
File1.py:
import inspect
def get_current_filename():
return inspect.stack()[1][1]
File2.py:
import File1
x = File1.get_current_filename()
print(x)
Output:
C:\<omitted>\File2.py
The first [1]
indicates to look at the second frame in the call stack (the first frame being the location that called inspect.stack
, the second being the location that called that), the second [1]
gets the filename from the frame.