Woltan
Woltan

Reputation: 14033

Check if class B is subclass of class A which is located in the same module

With the following setup of the two files a.py

#File a.py
import imp
import inspect

class A(object):
    pass

if __name__ == "__main__":
    mod = imp.load_source("B", "b.py")
    for _, c in inspect.getmembers(mod, inspect.isclass):
        print issubclass(c, A) 

and

#b.py
from a import A

class B(A):
    pass

How do I check in file a.py if a class found in b.py is a subclass of A.

The attempt you see in a.py results in two False being printed. Since B is a subclass of A how do I check it crrectly?

Upvotes: 0

Views: 123

Answers (1)

woockashek
woockashek

Reputation: 1638

I have found the following solution:

#File a.py
import imp
import inspect

class A(object):
    pass

if __name__ == "__main__":
    mod = imp.load_source("B", "b.py")

    #self import
    import a

    for _, c in inspect.getmembers(mod, inspect.isclass):
        print issubclass(c, a.A)

but still I don't have any idea why it works (while your solution doesn't)

Upvotes: 2

Related Questions