module import search path strangeness

Peter Otten __peter__ at web.de
Tue Aug 12 17:59:40 CEST 2008


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



More information about the Python-list mailing list