
On Sun, Dec 28, 2014 at 4:42 PM, Chris Angelico <rosuav@gmail.com> wrote:
I mainly did up this patch to see how hard it would be, and now it's turned out to be fairly simple, I'm curious as to whether it would actually be useful to people.
At the point where a global/builtin name lookup is about to raise NameError, first try calling a Python function, along the same lines as __getattr__. If that function hasn't been defined, raise NameError as normal; but if it has, let it either raise NameError or return some object, which is then used as if the name had been bound to it.
Patch is here: http://bugs.python.org/issue23126
The idea is to allow convenient interactive use; auto-importing modules is easy, and importing names from modules ("exp" --> math.exp) can be done easily enough too, given a list of modules to try.
It's probably not a good idea to use this in application code, and I definitely wouldn't encourage it in library code, but it has its uses interactively.
I find it weird that it's *really truly* global, instead of being scoped to a single global namespace. Random thoughts: http://bugs.python.org/issue22986 enables a similar feature for module attribute lookups, which is one substantial source of "global" lookups. (Also it's been waiting for a review for some time, *coughcough* ;-)). If evaluating a specific piece of code, you can already pass an arbitrary dict-like object as the globals argument to exec, with whatever __getitem__ you want. Of course the built-in REPL doesn't provide any way to set the interactive namespace's globals object, but it could, or it'd be easy to implement in a REPL like IPython. You could achieve a similar effect by assigning a custom object to the interactive namespace's __builtins__ variable. -n -- Nathaniel J. Smith Postdoctoral researcher - Informatics - University of Edinburgh http://vorpus.org