Package organization

Graham Ashton gashton at cmedltd.com
Wed Nov 19 05:06:03 EST 2003


On Tue, 18 Nov 2003 16:38:15 -0800, Robert Ferrell wrote:

> I have a question about how to organize modules in a package.  I think
> there is something fundamental that I am missing.  Say I'm creating a
> package,
> GreatPackage, which has three sub-packages, myUtilities, GoodStuff,
> MoreGoodStuff.
> 
> The directories look like:
> 
> GreatPackage
>      |
>      |-- myUtilities
>      |
>      |-- GoodStuff
>      |
>      |-- MoreGoodStuff
> 
> What is the right way for modules in GoodStuff and MoreGoodStuff to
> refer to modules etc... in myUtilities?

There's a PEP that recommends that when importing things you refer to them
explicitly; i.e. inside GoodStuff you'd say 

  import GreatPackage.myUtilities

rather than just 

  import myUtilities

I've only benefitted from doing it that way myself in large apps that have
had many packages with sub packages. It keeps you safe from module name
clashes at different levels of the hierarchy (not that I think they're a
sensible thing to have). By name clashes I mean if you have modules
set up like this:

  lib
  shoe.lib
  shoe.fruit

then you can't get at the top level lib module from inside shoe.fruit.

> from GreatPackage.myUtilities import aUtilityThingy
> 
> in a module in GoodStuff, then the whole package gets loaded,
> including MoreGoodStuff.

MoreGoodStuff won't get loaded if you import GreatPackage, unless
GreatPackage/__init__.py causes it to be loaded. Obviously, if something
in myUtilities imports something from MoreGoodStuff then python will
attempt to load MoreGoodStuff when importing myUtilities.

Also, because you're importing something from inside a module using the
"from" style imports you're risking running into circular reference
problems. In my experience from imports are best avoided, unless you're
importing a module from a package.

> What are guidelines for developing/deploying packages which contain
> pacakges?

For deploying, have you looked at distutils?

-- Graham




More information about the Python-list mailing list