'Find which line a variable was defined on after importing file

I can use the ast module in Python to look for ast.Assign nodes or FunctionDef nodes and look for the name of the variable being assigned to. But my issue is code like this

try:
    from some_third_party_library import my_func
except ImportError:
    def my_func():
        return 'this is a fallback'

which may cause my_func to be defined in two places and you basically can't know without running the code. Is there a way for me to import this code file and then find which line my_func was defined on after running it?



Solution 1:[1]

If you just need to know what file it was defined in:

from module1 import my_func

print(my_func.__globals__['__file__'])

If for example, this is the content of module1.py:

try:
    from module2 import my_func
except ImportError:
    def my_func():
        return 'this is a fallback'

And this is module2.py:

not_my_func = 'something else'

If you need the line number, this is a way to get it:

import inspect
from module1 import my_func

print(my_func.__globals__['__file__'])
print(inspect.findsource(my_func)[1]+1)

Example output:

C:\Python\project\module1.py
4

Depending on what version of Python you're using, and how much speed matters, since the above needs inspect anyway, this is a nice solution as well:

import inspect
from module1 import my_func

print(inspect.getsourcefile(my_func))
print(inspect.getsourcelines(my_func)[1])

Example output:

C:\Python\project\module1.py
4

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Grismar