Python's import mechanism in pseudocode.

by jesse in ,

Brett Cannon's gone and made something incredibly useful - he mocked up the python import system in simple pseudo code here this is great as it actually answers some questions I had on sunday when I was boggling at some import-isms I was seeing. To quote:

At this point I have written out the code for how import goes about looking for a module. This covers the use of sys.meta_path, sys.path, sys.path_importer_cache, and sys.path_hooks. I have not covered how the bytecode/source dance works or extension modules. Writing up those two will show why Python makes so many stat calls when it does an import.

From Now you too can know how import (roughly) works!

I for one am looking forward to seeing the rest of this work.

As an aside: Did you know that module preference is in path load order? For example - say I I had /usr/lib/python2.4/ and later I had /home/jesse/ and sys.path.append'ed('/home/jesse') - the initial would be seen by the loader first, and the later version would not be loaded.

I knew this, but I didn't know ((I'm blonde, I have moments)) it - the same thing happens when you "import os" and later "import os" - you don't reload the module, the original import is the one in effect.

In order to get modules loaded you know conflict with something in the stdlib (say, a working popen2) you should always sys.path.insert(0, ...).