import X between submodules in a package

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Dec 19 03:46:00 EST 2007


Donn Ingle a écrit :
> Hi, I'm sure this is a FAQ, but I have just not found clarity on the
> web/docs.
> 
> (using monospaced type to show the tree)
> trunk:$ tree
> .
> fp
> |-- fontypython
> |   |-- __init__.py
> |   |-- cli.py
> |   |-- config.py
> 
> (I start it all with ./fp)
> 
> fp says:
> import cli
> 
> cli.py says:
> import os
> import config
> 
> config.py says:
> print os.environ['HOME']
> 
> I get a NameError in config.py
> 
> If I add 'import os' to config.py all is well.
> 
> So, I guess I am confused about the 'scope' of what gets imported where. I
> am thinking that if one module (py file) does *import os* something and
> *then* imports another module - the second module should have access to os
> too?

Definitively no. This would make the second module dependent on the 
context in which it is used, which would be a VeryBadThing(tm). Each 
Python module is it's own _distinct_ namespace, and only depend on the 
name  it explicitely imports or defines. FWIW, it's the whole point of 
*modules* (by opposition to 'includes' à la PHP).

>  I imagine myself "standing" inside cli.py at this point and saying "well I
> can see os, and I'm bringing config *into* this space, so they should be
> able to see os too."

I can tell you from experience (with languages that work that way, cf 
above) that this usually leads to the worst possible mess, even if 
you're being careful.

> How do I structure things so that I don't have endless repetitions of import
> in every py file within my package directory?

Having explicits imports in each module is good wrt/ readability. Now if 
you have a huge common set of imports in each and every submodule of a 
package, you can of course factor them out in a distinct submodule and 
just do a 'from myimports import *' at the top of the others submodules...



More information about the Python-list mailing list