Python’s import mechanism in pseudocode.

June 5th, 2007 § 3 comments

Brett Cannon’s gone and made some­thing incred­i­bly use­ful — he mocked up the python import sys­tem in sim­ple pseudo code here this is great as it actu­ally answers some ques­tions I had on sun­day when I was bog­gling at some import-isms I was see­ing. To quote:

At this point I have writ­ten out the code for how import goes about look­ing for a mod­ule. This cov­ers the use of sys.meta_path, sys.path, sys.path_importer_cache, and sys.path_hooks. I have not cov­ered how the bytecode/source dance works or exten­sion mod­ules. Writ­ing 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 look­ing for­ward to see­ing the rest of this work.

As an aside: Did you know that mod­ule pref­er­ence is in path load order? For exam­ple — say I I had /usr/lib/python2.4/foo.py and later I had /home/jesse/foo.py and sys.path.append’ed(‘/home/jesse’) — the ini­tial foo.py would be seen by the loader first, and the later ver­sion would not be loaded.

I knew this, but I didn’t know44 it — the same thing hap­pens when you “import os” and later “import os” — you don’t reload the mod­ule, the orig­i­nal import is the one in effect.

In order to get mod­ules loaded you know con­flict with some­thing in the stdlib (say, a work­ing popen2) you should always sys.path.insert(0, …).

4

  1. I’m blonde, I have moments444

4

What's this?

You are currently reading Python’s import mechanism in pseudocode. at jessenoller.com.

meta