Module/package hierarchy and its separation from file structure

Carl Banks pavlovevidence at
Sat Jan 26 01:48:38 CET 2008

On Jan 25, 6:45 pm, Ben Finney <bignose+hates-s... at>
> "Gabriel Genellina" <gagsl-... at> writes:
> > You can also put, in animal/
> > from monkey import Monkey
> > and now you can refer to it as org.lib.animal.Monkey, but keep the
> > implementation of Monkey class and all related stuff into
> > .../animal/
> This (as far as I can understand) is exactly the solution the original
> poster desired to "shoot down", for reasons I still don't understand.

Come on, the OP explained it quite clearly in his original post.  Did
you guys even read it?

The module where org.lib.animal.Monkey is actually defined should be
an implementation detail of the library, but simply importing Monkey
into org.lib.animal doesn't quite make it one.

If a user pickles a Monkey class, and then the OP decides to refactor
the Monkey class into a new module (say
org.lib.animal.primate.monkey), then the user would not be able to
unpickle it.  Because, you see, pickles record the module a class is
defined in.  So, now the user has to worry about where Monkey is
actually defined.  It is not an implementation detail.

The solution is to modify the class's __module__ attribute as well as
importing it, as I've already pointed out:

from org.lib.animal.monkey import Monkey
Monkey.__module__ = 'org.lib.animal'

This should be enough to satisfy the OP's requirements, at least for
classes, without softening the one-to-one module-to-file relationship,
or using "hacks".

In fact, I'd say this is good practice.

Carl Banks

More information about the Python-list mailing list