Q on naming nested packages/modules

kj no.email at please.post
Tue Sep 1 17:58:00 CEST 2009

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:

  |-- 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

  |-- 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.

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?

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



More information about the Python-list mailing list