views:

1075

answers:

2

Assume I have this barebones structure:

project/
  main.py
  providers/
    __init.py__
    acme1.py
    acme2.py
    acme3.py
    acme4.py
    acme5.py
    acme6.py

Assume that main.py contains (partial):

if complexcondition():
  print providers.acme5.get()

Where __init__.py is empty and acme*.py contain (partial):

def get():
  value=complexcalculation()
  return value

How do I change these files to work?

Note: If the answer is "import acme1", "import acme2", and so on in __init__.py, is there a way to accomplish that without listing them all by hand?

+1  A: 

This question asked today, Dynamic Loading of Python Modules, should have your answer.

Van Gale
Not quite what I was hoping for, but it led me to a workable solution, thanks.
arantius
+2  A: 

If I'm reading your question correctly, it looks like you're not trying to do any dynamic importing (like in the question that Van Gale mentioned) but are actually trying to just import all of the modules in the providers package. If that's the case, in __init__.py you would want to have this statement:

__all__ = ["acme1", "acme2", "acme3", "acme4", "acme5", "acme6"]

Then to import everything you would use from ... import *

from providers import *

And then instead of using the package name explicitly in the code, you would just call the imported classes

acme1.get()
acme2.get()

If you have enough modules in the providers package that it becomes a problem populating the __all__ list, you may want to look into breaking them up into smaller packages or storing the data some other way. I personally wouldn't want to have to deal with dynamic importing schennagins every time I wanted to re-use the package.

TwentyMiles