Finding the filename and file path of a function in Python

Viewed 1845

I have large number of python files where classes are also inheriting and overriding methods. I am tracking calls of the functions. Is there a way I can get the details of the function (where it is located in which file) without the actual call of the function (for example, just by passing object and function name)?

Not to forget that objects are dynamic. So just listing all function names of the project isn't useful.

File 1:

class ABC(DEF):
    def Start(self):
        pass

File 2:

class XYZ(DEF):
    def Start(self):
        pass

.

.

.

File n:

class PQR(AQZ):
    def Activity(self):
        obj = ABC()
        # How to know in which file, the function Start is defined
        obj.Start()
1 Answers

Take a look at the inspect module. It's not always going to work (builtins implemented in C won't necessarily have line numbers, or even associated files, since some modules like sys are baked into the core interpreter, not distributed as separate files), but it's the closest you're going to get to what you're looking for.

Updating your example to provide info on the origin of things:

import inspect

class PQR(AQZ):
     def Activity(self):
        obj = ABC()
        # How to know in which file, the function Start is defined
        try:
            _, lineno = inspect.getsourcelines(obj.Start)
            srcfile = inspect.getsourcefile(obj.Start)
        except TypeError:
            print("{!r} is a built-in".format(obj.Start))
        else:
            print("{!r} comes from {!r}, line {}".format(obj.Start, srcfile, lineno))
        obj.Start()
Related