Q on naming nested packages/modules

Benjamin Kaplan benjamin.kaplan at case.edu
Tue Sep 1 12:42:51 EDT 2009


On Tue, Sep 1, 2009 at 11:58 AM, kj<no.email 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.
>
>
> 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.
>

Take everything in ham.py and stick it in ham/__init__.py instead.
This will give you the behavior you're looking for (don't import
spam.ham.__init__. Everything in __init__.py is loaded into spam.ham)
> TIA!
>
> kynn
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list