Reputation: 181
# test1.py
class DatabaseEngine(object):
pass
# test2.py
from test1 import DatabaseEngine
class OracleEngine(DatabaseEngine):
pass
# test3.py
from test1 import DatabaseEngine
class MysqlEngine(DatabaseEngine):
pass
# test4.py
# try 1
from test1 import DatabaseEngine
print DatabaseEngine.__subclasses__() # returns empty list
# try 2
from test2 import DatabaseEngine
from test3 import DatabaseEngine
print DatabaseEngine.__subclasses__() # returns [oracle, mysql]
Why does #try1 fails to recognize the subclasses but #try 2 recognizes its sub classes.
I want to use __ subclasses() __ in test4.py without doing
from test2 import DatabaseEngine
from test3 import DatabaseEngine
Is there a way to do it?
Upvotes: 1
Views: 993
Reputation: 981
Try 1 doesn't work b/c importing explicitly evaluates the code in that module. You do not import the modules containing your subclasses in try 1, so they do not get evaluated.
If you choose to keep your subclasses in different modules and want access them all, then there will have to be at least one module where you import them all.
I'd recommend creating another file containing your subclass implementations, importing them there, then when you need the subclasses, import this one file.
Upvotes: 1