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

Brett Cannon brett at python.org
Tue Jan 30 23:21:49 CET 2007


On 1/30/07, Ron Adam <rrr at ronadam.com> wrote:
> Brett Cannon wrote:
> > 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
>
>
> But if you try to run a module in a package, vs from a package, with relative
> from . imports, you will get:
>
>       ValueError: Attempted relative import in non-package
>
> And there is no __path__ attribute to look at since no package has been imported
> yet.

Yeah, I have been bitten by that.  You need to have that initial
package import.  I got nailed by this when using '-m' and a module
contained within a package for executing tests.

>
> So you need to import the package first, and then you may not import the correct
> package even then if there is another package or module with the same name.
>

Well, just don't do that.  =)  You really shouldn't have multiple
things with the same name in sys.path.  But as you noticed, you can
control it with sys.path if you really need to.

I just don't see this as a common enough problem to warrant
documenting it somewhere (and I have no clue where that "somewhere"
would be).

-Brett



More information about the Python-ideas mailing list