__missing__ for the top-level Python script

Skip Montanaro skip.montanaro at gmail.com
Wed Nov 12 15:56:58 CET 2014


> No bites? I'd have thought there'd be a few crazy ideas thrown out in
> answer to this.

I was on vacation for a few days, so haven't been all that attentive
to my mail. I have an autoload module which does something similar
(note the Python 2.x syntax):

import sys, inspect, traceback, re

def autoload_exc(ty, va, tb):
    mat = re.search("name '([^']*)' is not defined", va.args[0])
    if mat is not None:
        modulename = mat.group(1)
        print >> sys.stderr, "autoloading", modulename
        f_locals = tb.tb_frame.f_locals
        f_globals = tb.tb_frame.f_globals

        exec "import " + modulename in f_locals, f_globals
        exec tb.tb_frame.f_code in f_locals, f_globals
    else:
        traceback.print_exception(ty, va, tb)

sys.excepthook = autoload_exc

which works about as you'd expect:

>>> sys.excepthook
<function autoload_exc at 0x1a5e140>
>>> math.sin(42)
autoloading math
-0.9165215479156338
>>> string.uppercase
autoloading string
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

I can't see a lot of people wanting this (I normally have its import
commented out in my PYTHONSTARTUP file), and I think it would probably
be bad practice for new users of the language.

Skip



More information about the Python-list mailing list