I have a directory structure:
example.py
templates/
__init__.py
a.py
b.py
a.py
and b.py
have only one class, named the same as the file (because they are cheetah templates). For purely style reasons, I want to be able to import and use these classes in example.py
like so:
import templates
t = templates.a()
Right now I do that by having this in the template folder's __init__.py
:
__all__ = ["a", "b"]
from . import *
However, this seems pretty poor (and maybe superfluous), and doesn't even do what I want, as I have to use the classes like this:
t = templates.a.a()
Thoughts?
To avoid repeating
from <whatever> import *
25 times, you need a loop, such as:I'm putting the meaningful code in a function because (a) it's always best [[for performance and to avoid polluting the module's namespace]], (b) in this particular case it also avoids accidents (e.g., some submodule might define a name
thismod
ormodnames
... so it's important to keep those names that we're using in the loop local to the function, not module globals, so they can't be accidentally trampled;-).If you want to enforce the fact that a module named
modname
only has one class (or other global) with the same name, change the last statement of the loop to:In your
__init__.py
:Now all of
a
's contents will be intemplates
, as will all ofb
's contents.I didn't even know you could have
from . import *
. My python interpreter complains about such statements. Still, to your problem, you could do:you can now use
other solution: