Virgil Gheorghiu
Virgil Gheorghiu

Reputation: 533

Find the path of the file loading base class defining variable

I have the following sample code:

$ cat f1.py
class classA(object):
    var1 = "something"

$ cat f2.py
from f1 import classA
class classB(classA):
    pass

$ cat loader.py
#!/usr/bin/python -tt
from f2 import classB

if __name__ == "__main__":
    for cl in classB.__mro__:
        print cl.__module__

$ ./loader.py
f2
f1
__builtin__

I would like to print the absolute or relative path of the file(s) where classB (f2.py) and classA (f1.py) are defined. Specifically, I would like to know the file of the class that actually defines var1. If I have a real module, then I get e.g. mymodule.f1 which it looks like I have to search in sys.path to actually find it on disk.

Is there an easier way? Why don't classes (i.e. non-instances) have a __file__ attribute?

Upvotes: 1

Views: 53

Answers (2)

Virgil Gheorghiu
Virgil Gheorghiu

Reputation: 533

The easiest thing to do is:

sys.modules[__module__].__file__

We modify loader.py above to say:

if __name__ == "__main__":
    for cl in classB.__mro__:
        print sys.modules[cl.__module__].__file__

$ ./loader.py
/Users/virgilg/Code/testing/python/f2.pyc
/Users/virgilg/Code/testing/python/f1.pyc

To answer the question "which file/class defines var1?", we can do:

if __name__ == "__main__":
    oldCl = None
    for cl in classB.__mro__:
        if not hasattr(cl, 'var1'):
            break
        oldCl = cl


    print sys.modules[oldCl.__module__].__file__

$ ./loader.py
/Users/virgilg/Code/testing/python/f1.pyc

Upvotes: 1

Lee Dunham
Lee Dunham

Reputation: 117

You want the inspect module.

import inspect
inspect.getfile(ClassA.__class__)
inspect.getfile(ClassB.__class__)

Upvotes: 2

Related Questions