12

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
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
cap
  • 365
  • 2
  • 14
  • Shouldn't `get_subclass` return something? And you'll need to import `project.src.subclass`. – robx Aug 20 '18 at 20:14
  • Import where? It should return something but it doesn't. If I have 4 subclasses in different files, should I import each? I guess it'd make more sense then to keep them in one file. – cap Aug 20 '18 at 20:33
  • 3
    Import at all. If the module with the subclass is never loaded, then the python interpreter can't know that a subclass exists. – robx Aug 20 '18 at 20:48

1 Answers1

24

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.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • 1
    After a few hours of head-scratching, I stumbled upon this realization. – Dave Liu Feb 01 '21 at 17:33
  • just a note for those who reads, don't try to test it on the same file as your base class! test the result in a separate file. – Omid Dec 26 '21 at 16:44