module import search path strangeness

tow toby.o.h.white at googlemail.com
Tue Aug 12 19:36:47 CEST 2008


On Aug 12, 4:59 pm, Peter Otten <__pete... at web.de> wrote:
> tow wrote:
> > On Aug 12, 9:56 am, Peter Otten <__pete... at web.de> wrote:
> >> tow wrote:
>
> >> > Basically, I had thought that import and imp.find_module used exactly
> >> > the same
> >> > search path, but the above example shows that at least in this
> >> > circumstance they
> >> > don't; import is picking up additional search paths from somewhere -
> >> > what am I missing?
>
> >> Grepping through the django source finds
>
> >> ./trunk/django/core/management/__init__.py:
> >> sys.path.append(os.path.join(project_directory, os.pardir))
>
> > Hmm. It turns out that that is indeed the issue, but in a way that
> > wasn't immediately obvious to me. Looking at it in more context:
>
> >     sys.path.append(os.path.join(project_directory, os.pardir))
> >     project_module = __import__(project_name, {}, {}, [''])
> >     sys.path.pop()
>
> Ouch.
>
> > So, to answer my original question, the difference in search behaviour
> > between "import" and "imp.find_module" is that the former might not
> > look at sys.path at all if the module has already been loaded, while
> > the latter will only search on the current sys.path.
>
> > Am I right?
>
> Yes. 'import' looks up the file in a cache, the sys.modules dictionary,
> before it falls back to the more costly alternatives.
>
> Peter

Thanks, at least I understand what's going on now.

Toby



More information about the Python-list mailing list