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?

3
  • 2
    What have you tried? Have you read about the import statement? Since this is what import does, I can't understand your question. Commented Jun 11, 2009 at 16:22
  • you can check answers at this similar question Commented Jun 11, 2009 at 16:22
  • Giorgio's answer was very usefull Commented Jun 12, 2009 at 7:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't like the use of exec(), sorry

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.