Why the default sys.path[0] insertion? (It breaks my code.)

Robb Shecter rs at onsitetech.com
Fri Dec 20 12:20:52 EST 2002


Martin v. Löwis wrote:
> Robb Shecter wrote:
> 
>> 1) This behavior is inconsistent:  Programmers cannot use relative 
>> package specs in the import statement.  But in this one case, the 
>> import statement is being interpreted relatively!
> 
> 
> Why do you say this? You surely can use a relative import inside a 
> package. In fact, this is what probably causes the problem for you right 
> now: You do "import db", and expect this to be "mpm.db", but it happens 
> to become "db" because of the sys.path modification.

No no no...  I do (for example) "import db"and expect it to be "db", but 
it ends up being "mpm.db".  I'm trying to follow the rules, and not do 
relative imports, because as I understand it, you can't do them.  But 
I'm finding that imports *are* sometimes, occasionally, interpreted 
relatively.  (ie, when the file doing the importing happens to be the 
first one executed by the interpreter.)

THIS is what mystifies me about the policy of path[0] insertion; it's 
not predictable, so I wouldn't depend on its value.





> 
>> 2) I guess that a workaround would be either a) Make a dummy script in 
>> the top-level directory that relays the call to the one in the 
>> subdirectory, or b) Somehow configure my environment to to 
>> sys.path.pop(0).  I'm not sure which solution is cleaner.
> 
> 
> Solution a) is the common approach. However, another solution is to 
> avoid relative imports: Instead of importing "db", import "mpm.db".
> It then won't matter if there is a db package or module on sys.path.
> 
> Regards,
> Martin
> 





More information about the Python-list mailing list