0

I have two files. /a/a.py and /b/b.py

In /b/b.py, I have a func foo(). In /a/a.py, I imported the func foo().

I want to add a line in foo() to print the file path which imported and used this func. In this case, /a/a.py

I tried to use print(__file__) but it only shows the path of /b/b.py

Is there any package that works for this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
黯星座
  • 3
  • 1
  • Modules are only imported once. If a second module `c.py` also imports, `b` will not know it happened. – tdelaney Aug 18 '22 at 17:12

1 Answers1

0

the imported part is hard due to how importlib works, but the use part is rather simple, you can easily get the information of the caller by inspecting the stack using the inspect module, this is only possible in Cpython though.

adopted from this answer

import inspect

def a():
    curframe = inspect.currentframe()
    calframe = inspect.getouterframes(curframe, 2)
    print('caller name:', calframe[1][3])
    print('caller file:', calframe[1][1])

def b():
    a()

b()
Ahmed AEK
  • 8,584
  • 2
  • 7
  • 23