0

The primary problem I'm trying to solve is how to detect all the subclasses of a particular class. The reason I'm unable to use __subclasses__ is that the child classes aren't yet accessible in the context from which I'm attempting to access them.

The folder structure I'm working with looks like this:

    main.py
    projects/
        __init__.py
        project.py
        some_project_child.py

What I'd like to do is get a list of all subclasses of Project (defined in project.py) from main.py.

I'm able to do this by doing:

from projects.project import Project

from projects.some_project_child import SomeProjectChild

Project.__subclasses__

The aspect of this approach I'd like to avoid is having to add an import line every time I add a new project file/class. I realize I can do this by iterating over the files in the directory and import each one's contents but is there a cleaner more pythonic manner of handling this?

Raphi
  • 410
  • 4
  • 17
  • 1
    Have you seen [this answer](https://stackoverflow.com/a/1057534/933770)? – Ali Momen Sani Dec 03 '17 at 19:37
  • 2
    Take a look at the answers to the question titled [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time). – martineau Dec 03 '17 at 19:42

1 Answers1

1

It is the nature of a non-compiled language like Python that it is impossible to do anything like this without importing. There is simply no way for Python to know what subclasses any class has without executing the files they are defined in.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895