How to get the file name where the function is defined?

Hi Terry,

The inspect module seems to use f.__code__.co_filename.
Using __import__(g.__module__).__file__ looked cool … except one case I found:

# test_script.py
from mylib import dcor

@dcor
def g(): pass

if __name__ == "__main__":
    print(__import__(g.__module__))
    print(__import__(g.__module__).__file__)

If you launch this script,

>py -i test_script.py
<module '__main__' from 'C:\\usr\\home\\lib\\python\\test-py\\test_script.py'>
C:\usr\home\lib\python\test-py\test_script.py
>>>

So far, so good. However, it fails when I continue with interactive input!

>>> __import__(g.__module__)
<module '__main__' (<_frozen_importlib_external.SourceFileLoader object at 0x00000208D3B08D60>)>
>>> __import__(g.__module__).__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module '__main__' has no attribute '__file__'. Did you mean: '__name__'?
>>>

I guess “frozen” has something to do with it…, but I don’t know why. :cold_face: