Autoloader (was Re: CSV Error)

Mark Lawrence breamoreboy at yahoo.co.uk
Sun Dec 28 11:14:13 EST 2014


On 28/12/2014 15:38, Chris Angelico wrote:
> 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
>

I'd raise a tracker issue so it's easier to find in the future.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list