[Python-Dev] making the import machinery explicit

Nick Coghlan ncoghlan at gmail.com
Sun Apr 15 13:26:30 CEST 2012

Hooray for finally having this to the point where it has been pushed to trunk :)

On Sun, Apr 15, 2012 at 8:16 AM, Brett Cannon <brett at python.org> wrote:
> Once again, it's just code that needs updating to run on Python 3.3 so I
> don't view it as a concern. Going from list.append() to list.insert() (even
> if its ``list.insert(hook, len(list)-2)``) is not exactly difficult.

I'm not sure you can so blithely wave away the "check this before the
standard hooks" problem. If the recommended approach becomes to insert
new hooks at the *start* of path_hooks and meta_path, then that should
work fairly well, since the new additions will take precedence
regardless of what other changes have already been made. However,
trying to be clever and say "before the standard hooks, but after
everything else" is fraught with peril, since there may be hooks
present in the lists *after* the standard ones so naive counting
wouldn't work.

As far as the guidelines for managing the import state go, it may be
worth having public "importlib.default_path_hooks" and
"importlib.default_meta_path" attributes.

Then "clearing" the hooks would just be a matter of resetting them
back to defaults: "sys.path_hooks[:] = importlib.default_path_hooks".
You could also locate them in the hooks list correctly by checking
"for i, hook in enumerate(sys.path_hooks): if hook is
importlib.default_path_hooks[0]: break"

Alternatively, it may be simpler to just expose a less granular
"reset_import_hooks()" function that restores meta_path and path_hooks
back to their default state (the defaults could then be private
attributes rather than public ones) and invalidates all the caches.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list