0

I need to to dynamically import identically named classes from files in a subfolder. The classes have different implementations in every file. After the import I need to create an instance of each class and store them in a data structure so I can invoke each function in thee instances.

folder structure:

./main.py
./players/player1.py
./players/player2.py
./players/player3.py
./players/player4.py

player1.py

class PlayerClass():
    def doStuff():
        stuff implementation 1

player2.py

class PlayerClass():
    def doStuff():
        stuff implementation 2

So main.py will import all PlayerClasses from these files and create once instance each to then be able to call functions like doStuff form each instance. Something like:

importedClasses[0].doStuff()

I have managed to extract file names but I can't get the import to work from a subfolder and I can't import them as unique objects and store them in a list or similar either.

Atto
  • 152
  • 9

1 Answers1

1

Here is one approach

from glob import glob
from importlib.machinery import SourceFileLoader

modules = sorted(glob('players/player*.py'))

imported_classes = list(map(lambda pathname: SourceFileLoader(".", pathname).load_module().PlayerClass(), modules))

imported_classes[0].doStuff()

Here we are using glob to match the pathnames to the modules we would like to import. Then import them using the importlib module (SourceFileLoader).

Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
  • I'm getting only the first object into the list: ``` ``` – Atto Sep 15 '20 at 10:34
  • 1
    Ah now it works! It doesn't seem ordered but that doesn't matter. Thanks! – Atto Sep 15 '20 at 10:39
  • The sorting in glob depends on your fs I think (see [here](https://stackoverflow.com/questions/6773584/how-is-pythons-glob-glob-ordered)), but you can still sort the list with `sorted()` – Tibebes. M Sep 15 '20 at 10:48
  • update the line that sets the `modules` list as `modules = sorted(glob('players/player*.py'))` and it should be okay – Tibebes. M Sep 15 '20 at 10:48