Importing modules

Diez B. Roggisch deets at nospam.web.de
Wed Jan 7 12:39:16 EST 2009


e4me4m at gmail.com wrote:

> Coming from a scripting background where we used to write everything
> into one script, I'm now going modular with Python. I place related
> functions in one module, and other functions in other modules.
> 
> This all works OK, but I'm a bit confused about importing modules from
> the standard library. For example, say 3 of my 12 modules use os and
> os.path. Right now, I have import statements in all 3 modules that
> import both os and os.path. This seems wrong to me.
> 
> I read the docs and understand that before loading a module that
> Python is smart enough to look and see if it's already loaded, so
> there is no performance issue (it would seem), but I was thinking
> there is probably a way to load all the modules I need in some orderly
> fashion without having these multiple import statements in my separate
> modules.
> 
> Could someone point me to some docs that explain the Python way of
> loading modules when breaking old, big (everything in one script) into
> more manageable modular scripts?

There is no way around the multiple imports. Or, at least not a clean way -
you *could* stuff things into __builtin__ in one module, effectively making
it available globally.

But this is a hack at best, and certainly not the way to go.

The thing about modularization is that you want single pieces of code that
can be read and understood and extended by themselves (even if embedded and
useful in - or only in - a larger context).

So the seemingly unnecessary imports serve documentation purposes - what is
actually needed by the current module. 

Diez



More information about the Python-list mailing list