[Python-ideas] Import and '..', '../..' in serach path.

Brett Cannon brett at python.org
Tue Jan 30 20:32:21 CET 2007


On 1/30/07, Ron Adam <rrr at ronadam.com> wrote:
>
> In order to resolve a path conflict where I'm working on several copies of the
> same package.  I found it useful to add the following near the top of modules in
> a package or sub package.
>
>
> Module in package:
>
>      import sys
>      sys.path = ['..'] + sys.path
>
>      import package.module          # Imports module in "this!" package.
>
>
> Note: There could still be conflicts if a module with the same name is in the
> same directory as the package.  But that's much less likely than one in the rest
> of the path.
>
>
> Module in sub-package:
>
>      import sys
>      sys.path = ['../..'] + sys.path
>
>      import package.subpackage.module   # finds "self" (subpackage) reliably.
>
>
> By explicitly adding the packages parent directory to the *front* of sys.path it
> resolves cases where imports using absolute imports, import modules from another
> package because they are found first in the search path.

Why aren't you using relative imports (e.g., ``from . import
module``)?  That should be doing exactly what you want.  That uses
__path__ which is set to the path of the package.

-Brett



More information about the Python-ideas mailing list