0

I have the following directory and file structure in my current directory:

├── alpha
│   ├── A.py
│   ├── B.py
│   ├── Base.py
│   ├── C.py
│   └── __init__.py
└── main.py

Each file under the alpha/ directory is it's own class and each of those classes inheirts the Base class in Base.py. Right now, I can do something like this in main.py:

from alpha.A import *
from alpha.B import *
from alpha.C import *

A()
B()
C()

And it works fine. However, if I wanted to add a file and class "D" and then use D() in main.py, I'd have to go into my main.py and do "from alpha.D import *". Is there anyway to do an import in my main file so that it imports EVERYTHING under the alpha directory?

pnus
  • 187
  • 1
  • 14

1 Answers1

0

depens what you are trying to do with the objects, one possible solution could be:

import importlib
import os

for file in os.listdir("alpha"):
    if file.endswith(".py") and not file.startswith("_") and not file.startswith("Base"):
         class_name = os.path.splitext(file)[0] 
         module_name = "alpha" + '.' + class_name
         loaded_module = importlib.import_module(module_name)
         loaded_class = getattr(loaded_module, class_name)
         class_instance = loaded_class()

Importing everything with * is not a good practice, so if your files have only one class, importing this class is "cleaner" ( class_name is in your case)

ilja
  • 2,592
  • 2
  • 16
  • 23