Simplifying imports?

Neal Norwitz nnorwitz at gmail.com
Tue Sep 13 01:25:30 EDT 2005


chapolim-colorado at bol.com.br wrote:
> I like to keep my classes each in a separate file with the same name of
> the class. The problem with that is that I end up with multiple imports
> in the beginning of each file, like this:
>
> from foo.Bar import Bar
> from foo.Blah import Blah
> from foo.Zzz import Zzz

Must ... resist ... temptation ... to ... complain ... about ... J...

> What I'd like to do would be to replace it all by a single line:
>
> from foo.* import *
>
> Of course, that doesn't work, but is there a way to do something like
> that?

In foo there is a file __init__.py, right?  If you have 3 class files
in foo: bar.py, baz.py, and bax.py, you're __init__.py could contain:

# __init__.py
from foo.bar import Bar
from foo.baz import Baz
from foo.bax import Bax
# end of __init__.py

Then, voila:

>>> import foo
>>> dir(foo)
['Bar', 'Bax', 'Baz', '__builtins__', '__doc__', '__file__',
'__name__', '__path__', 'bar', 'bax', 'baz']

You could write code in __init__.py to import all the files in foo/ if
you wanted.  That way you wouldn't have to explicitly list each file.
(Hint:  see os.listdir() and __import__().)

HTH,
n

PS.  I don't really like this approach.  It seems too implicit
(magical).




More information about the Python-list mailing list