Autoloader (was Re: CSV Error)

Chris Angelico rosuav at gmail.com
Sun Dec 28 10:38:45 EST 2014


On Mon, Dec 29, 2014 at 1:22 AM, Chris Angelico <rosuav at gmail.com> wrote:
> I wonder how hard it would be to tinker at the C level and add a
> __getattr__ style of hook...

You know what, it's not that hard. It looks largeish as there are four
places where NameError (not counting UnboundLocalError, which I'm not
touching) can be raised - LOAD_GLOBAL and LOAD_NAME, both of which
have a fast path for the normal case and a fall-back for when
globals/builtins isn't a dict; but refactoring it into a helper
function keeps it looking reasonable.

Once that's coded in, all you need is:

def try_import(n):
    try: return __import__(n)
    except ImportError: raise NameError("Name %r is not defined"%n)
import sys
sys.__getglobal__ = try_import

and then any unknown name will be imported, if available, and
returned. It's just like __getattr__: if it returns something, it's as
if the name pointed to that thing, otherwise it raises NameError.

Is anyone else interested in the patch? Should I create a tracker
issue and upload it?

ChrisA



More information about the Python-list mailing list