Hard times with packages and instances

Kay Schluehr kay.schluehr at gmx.net
Fri May 6 01:42:30 EDT 2005


Fredrik Lundh wrote:
> Kay Schluehr wrote:
>
> > I wonder why the isinstance() function is sensitive about the
import
> > path i.e. the result depends not only on the class and the instance
but
> > also on how a class is imported?
>
> isinstance uses class object identity.
>
> if you manage to import the same thing multiple times, you'll have
> multiple class objects representing the same source code, and is-
> instance won't work properly.

Importing a class/module multiple times does not cause the problem.
Writing

  import ForeignPackage.B as B1
  import ForeignPackage.B as B2

in C.py does not destroy the identity B1 == B2. Perhaps it is recovered
from sys.modules["ForeignPackage.B"]? It is not actually isinstance()
that depends on path information but the module recovery. The importer
seems to disambiguate to greedy.

>
> > Example:
> >
> > MyPackage/ Top-level package
> >       __init__.py Initialize package
> >       __me__.py                 Module used for setting Python-path
> >       A.py                      Use objects of ForeignPackage and
> >                                 subpackages
> >       ForeignPackage/ Don't touch!
> >             __init__.py         Initialize package
> >             B.py                Defines class B1
> >       MySubPackage/ Subpackage
> >             __init__.py         Initialize subpackage
> >     C.py                Defines instance checker for B1 instances
>
> in my newsreader, it looks like the C.py module is defined some-
> where inbetween MyPackage and MyPackage/ForeignPackage.
> what file system are you using? ;-)

This is surprisingly irrelevant. I used __me__.py for several projects
under Win2K without harm. Python seems to be more intelligent in path
handling than Windows.

> (I don't have the energy to decipher your convoluted import
> and path-manipulation code;
> but my intuition tells me that if
> you flatten the hierarchy, put MyPackage and ForeignPackage
> at the same level, and stop messing with the path inside the
> __init__ files, your problems will just disappear).

Flattening the package structure would solve the problem as well as
destroying all file-system based packages and abandon them from Python.
A bad joke? Yes, but managing all code using a database instaed of an
OS dependent filesys would make sense to me. 

Ciao,
Kay




More information about the Python-list mailing list