Understanding .pth in site-packages

Philip Semanchuk philip at semanchuk.com
Sat Aug 27 23:01:11 EDT 2011

On Aug 27, 2011, at 6:49 PM, Josh English wrote:

> When I run: os.listdir('c:\Python27\lib\site-packages') I get the contents in order, so the folders come before .pth files (as nothing comes before something.)

That's one definition of "in order". =)

> I would guess Python is using os.listdir. Why wouldn't it?

If you mean that Python uses os.listdir() during import resolution, then yes I agree that's probable. And os.listdir() doesn't guarantee any consistent order. In fact, the documentation explicitly states that the list is returned in arbitrary order. Like a lot of things in Python, os.listdir() probably relies on the underlying C library which varies from system to system. (Case in point -- on my Mac, os.listdir() returns things in the same order as the 'ls' command, which is case-sensitive alphabetical, files & directories mixed -- different from Windows.)

So if import relies on os.listdir(), then you're relying on arbitrary resolution when you have a .pth file that shadows a site-packages directory. Those rules will probably work consistently on your particular system, you're developing a habit around what is essentially an implementation quirk.  


More information about the Python-list mailing list