Autoloader (was Re: CSV Error)

Chris Angelico rosuav at gmail.com
Sun Dec 28 10:50:29 EST 2014


On Mon, Dec 29, 2014 at 2:38 AM, Chris Angelico <rosuav at gmail.com> wrote:
> It's just like __getattr__: if it returns something, it's as
> if the name pointed to that thing, otherwise it raises NameError.

To clarify: The C-level patch has nothing about imports. What it does
is add a hook at the point where NameError is about to be raised,
allowing a Python function (stuffed into sys.__getglobal__) to control
what happens.

I do *not* recommend this for application code, and I would strongly
discourage it for library code, but it's handy for interactive work.
Like with Skip's hook, you could have a specific set of "from" imports
supported as well - here's a port of that script that uses this hook
instead:

"""
autoload - load common symbols automatically on demand

When a NameError is raised attempt to find the name in a couple places.
Check to see if it's a name in a list of commonly used modules.  If it's
found, import the name.  If it's not in the common names try importing it.
In either case (assuming the imports succeed), reexecute the code in the
original context.
"""

import sys

_common = {}
# order important - most important needs to be last - os.path is chosen over
# sys.path for example
for mod in "sys os math xmlrpclib".split():
    m = __import__(mod)
    try:
        names = m.__all__
    except AttributeError:
        names = dir(m)
    names = [n for n in names if not n.startswith("_") and n.upper() != n]
    for n in names:
        _common[n] = m

def _autoload_exc(name):
        if name in _common:
            return getattr(_common[name], name)
        else:
            return __import__(name)

sys.__getglobal__ = _autoload_exc

-- cut --

Note that I've removed the print-to-stderr when something gets
auto-imported. This is because the original hook inserted something
into the namespace, but this one doesn't; every time you reference
"exp", it'll look it up afresh from the math module, so it'd keep
spamming you with messages.

ChrisA



More information about the Python-list mailing list