Duplicate modules problem
Ben Hutchings
ben.hutchings at roundpoint.com
Thu Feb 22 21:51:08 EST 2001
Chuck Esterbrook <echuck at mindspring.com> writes:
<snip>
> I have a problem where Python creates duplicate modules in memory rather
> than reuse the same one. For example, a module in Pkg/Mod.py ends up in
> sys.modules under keys "Pkg.Mod" and "Mod" **pointing to two distinct
> modules**.
<snip>
> The problem stems from the fact that Python tracks modules by a relative,
> rather than absolute, path. A simple os.chdir() or a subtley in packages
> can cause this problem.
Python doesn't track paths at all. It has a name-indexed cache of
modules, accessible as sys.modules, which the import statement checks
and updates. It's entirely possible to load modules without checking
the cache and/or without updating the cache. It's also possible to
create a Python environment with all modules pre-loaded from some
location which might not be a file at all.
<snip example>
> I believe the solution is for Python to track modules by their
> absolute path. I don't know of any other resolution to the situation
> other than modifying Python in this manner. I also don't know of
> any disadvantage for Python to track modules by absolute path.
<snip>
File/directory linking in Unix means that a single file can have
multiple paths, and as I said above some environments don't load
modules from files at all. So your 'solution' would just move the
problem (a problem which you've created for yourself by abusing the
import statement, IMHO). I think the real solution is to set the
Python module path appropriately and to give consistent module names
to the import statement. If the behaviour of the import statement
really isn't what you want, use the lower-level module import
functions.
--
Any opinions expressed are my own and not necessarily those of Roundpoint.
More information about the Python-list
mailing list