0

I would like to import classes located into a folder named

some-dir/

and named class*.py

and finally instantiate them.

Wich is the best way to look inside the folder, import classes and instantiate them?

DrFalk3n
  • 4,926
  • 6
  • 31
  • 34

1 Answers1

0

Try:

import os
#get files
files = os.listdir("some-dir/")
classes = []
for f in files:
   #find python modules in file listing
   if(f.find(".py") != -1):
      #remove file extenstion
      f = f.rstrip(".py")
      #create string to add module to global namespace, import it and instantiate
      #class
      importStr = "global " + f +";import " + f + "; classes.append(" + f +"())"
      #execute the code
      exec(importStr) 

That's a first stab at it. This assumes you don't have any parameters to pass to the class instantiation.

Don't know if it works, but it's somewhere to start. The "exec" statement lets you execute strings as python code.

Hope this helps you in the right direction.

Jay Atkinson
  • 3,279
  • 2
  • 27
  • 41