I'm implementing a function that returns an object from the appropriate subclass. If I move SubClass
from base.py
, no subclasses appear for __subclasses__
. Are they required to be in the same file?
Perhaps the fact that I'm never importing directly subclass.py
hides the subclass from python? What can I do? I have even checked the attribute __mro__
and get_subclass
points to the right class.
# project/main.py
from project.src.base import get_subclass
obj = get_subclass(cls,name) # Returns an object of a subclass of cls
# project/src/subclass.py
from project.src.base import BaseClass
class SubClass(BaseClass):
pass
# project/src/base.py
def get_subclass(cls,name):
subclss = cls.__subclasses__ # This is returning an empty list
pass
class BaseClass(object):
pass
Python only runs code of modules that are imported. If you move code to a different module but never import it, Python does not know about its contents.
You have to import the files containing the subclasses you want accessible.
# project/src/__init__.py
import project.src.base # executes the ``BaseClass`` definition
import project.src.subclass # executes the ``SubClass`` definition
Note that it does not really matter where you import these - they must be imported before you need SubClass
to appear in __subclasses__
, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With