Cross-reference 'import' in a class hierarchy

Jp Calderone exarkun at intarweb.us
Tue Apr 8 14:08:04 EDT 2003


On Tue, Apr 08, 2003 at 01:12:07PM +0200, Marcus Alanen wrote:
> >> I continue to be amazed that there's simply no way to say
> >> 
> >>   import "../foo/ook.py"
> >> 
> >> as should be possible to implement any well-architected class hierarchy.
> >
> >  It's simple.  Code should not depend directly on code higher than it in
> >the package hierarchy.  If it does (and it isn't one of a few extremely rare
> >cases), it is misdesigned.
> >
> >  Code shallow in the hierarchy should manage required references to objects
> >required by code deep in the hierarchy by passing them around explicitly. 
> >Any other solution is just bunk.
> 
> Could you explain why using import via PYTHONPATH is different than
> import via current directory?
> 

  Because of how Python determines module identity.

  This line:

    "from foobar import t2 as t1"

  causes "foobar" to be imported, adding "foobar" to sys.modules, then
causes "foobar.t2" to be imported, adding "foobar.t2" to sys.modules, then
binds the local "t1" to that module object.

  This line:

    "import t2"

  causes "t2" to be imported.  Before it is -actually- imported, sys.modules
is checked for the string "t2" to see if the module has already been loaded. 
If it has, that module object is returned, but if it hasn't (and as far as
Python knows, it hasn't, only "foobar.t2" has been imported, and that is
clearly a different module), "t2" is added to sys.modules and the local "t2"
is bound to the new module object.

> [snip]
> 
> Why are the id:s different? That is, why do I get two copies of the A
> class?

  Hopefully you see now that there are two copies of A, because there are
two copies of the module.


> This leads (IMHO) to the fact that one _never_ should use "import X",
> (witness isinstance(t1.A(), t2.A) returning 0...) everything should go via
> PYTHONPATH. Which in turn means that you have to set PYTHONPATH for all
> programs. ?

  One could look at it that way.  One could look at it another way, too:
don't mix imports in such a way that the same module may be referred to by
more than one name.

  This doesn't always mean putting the base of every application in
PYTHONPATH, it just means being consistent about how you import modules.

> 
> Some insight into why this is done as it is would be helpful.
> 

  The whys I can only speculate on.  Maybe someone who had a hand in the
implementation or who has discussed this with such a person could give us a
hint.

  Jp

-- 
Somewhere, something incredible is waiting to be known.
                -- Carl Sagan
-- 
 up 19 days, 15:01, 4 users, load average: 0.10, 0.12, 0.23





More information about the Python-list mailing list