Hard times with packages and instances

Kay Schluehr kay.schluehr at gmx.net
Fri May 6 04:31:48 EDT 2005


Fredrik Lundh wrote:
> Kay Schluehr wrote:
>
> > > 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
>
> that doesn't import it more than once; Python uses a cache to hold
> modules, but the cache only works if Python can be sure that the
> modules are the same thing, based on the information in the *import*
> statement.  in this case, "ForeignPackage.B" is clearly the same
thing
> as "ForeignPackage.B".

Yes, that's what I did expect.

> if you change the path around (in your case, by adding MyPackage to
> the path, rather than relying on path-relative import), you'll
introduce
> multiple ways to import the same module, and the cache won't work
> properly.  and when the cache doesn't work, isinstance breaks down
> for the reason I stated.

Exactly. "ForeignPackage.B" and "MyPackage.ForeignPackage.B" are two
paths pointing to the same module but it will be imported twice because
the cache does not lookup a strong name ( e.g. a hash of the module )
but the import path. This may also be the reason why it is not possible
to import a module in an interactive session, than edit it and finally
re-import it into the same running session. The hash value would have
been changed but the path remains the same.

>
> > Flattening the package structure would solve the problem as well as
> > destroying all file-system based packages and abandon them from
Python.
>
> well, packages for just fine for me.

In some cases they do, in other they don't. The __me__.py module comes
from working with ClearCase where the Python package is not installed
by an installation routine relative to an existing Python path. The
package has to recognize it's own position somewhere relative to the
virtual directory which can be arbitrary. Installing the package under
site-packages/ is a no go.

> if you cannot get them to work,
> maybe you should stop doing things that don't work.

For shure, but people tend to do workarounds. So I did.

Regards,
Kay




More information about the Python-list mailing list