Q on naming nested packages/modules

Carl Banks pavlovevidence at gmail.com
Tue Sep 1 19:11:34 CEST 2009


On Sep 1, 8:58 am, kj <no.em... at please.post> wrote:
> I'm having a hard time getting the hang of Python's package/module
> scheme.  I'd like to find out what's considered best practice when
> dealing with the scenario illustrated below.
>
> The quick description of the problem is: how can I have two nested
> modules, spam.ham and spam.ham.eggs?
>
> Suppose I have a module (I'm not even sure this is the right word)
> called spam.ham, so I start out with the following file structure:
>
>   spam/
>   |-- ham.py
>   `-- __init__.py
>
> With this arrangement, the line
>
> import spam.ham
>
> ...in client code works as expected.
>
> But now suppose that I want to factor out some code in spam/ham.py
> to a helper module.  (The reason behind factoring out this new
> module is to "declutter" spam/ham.py, and improve its readibility.)
> My instinct (from my Perl past) is to put this factored-out code
> in a file spam/ham/eggs.py, i.e. to create the "nested" module
> spam.ham.eggs, which requires expanding the tree as follows
>
>   spam/
>   |-- ham/
>   |   |-- eggs.py
>   |   `-- __init__.py
>   |-- ham.py
>   `-- __init__.py
>
> ...and adding the following spam/ham.py to
>
> # spam/ham.py
> from . import eggs
>
> This doesn't work so well, because now spam/ham.py is not read.
> It seems that adding the spam/ham directory, or maybe adding the
> file spam/ham/__init__.py, causes spam/ham.py to be overlooked.

There's a hint here.

You can move the contents of ham.py into ham/__init__.py, and it'll
work the way you want, maybe with only a minor change or two.


> Clearly, I'm not playing this game right...
>
> What is considered "best practice" for the use case sketched above?
> Should I, e.g. rename the directory spam/ham something like spam/ham_
> and refer to the helper module as spam.ham_.eggs?  Or is some other
> convention preferred?

The way you were intending is often the approach people use.  I doubt
there are any detailed consensus recommendations about this in the
Python community.


> I consulted PEP 8, but besides recommending "short, all-lowercase
> names" for modules, it gives little guidance on the situation
> described above.

Of course it doesn't, PEP 8 is a style guide, not a project
organization guide.


Carl Banks



More information about the Python-list mailing list