
On 28/12/2014 16:42, Chris Angelico wrote:
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.
On Mon, Dec 29, 2014 at 6:46 PM, Mark Lawrence <breamoreboy@yahoo.co.uk> wrote:
+1 from me as I'm always forgetting the "obvious" imports such as sys and os when trying things interactively.
On Mon, Dec 29, 2014 at 11:37 AM, Steven D'Aprano <steve@pearwood.info> wrote:
An interesting idea, but I don't actually think much of it for interactive use. Having modules magically import themselves without an import is a bad habit for beginners to learn, and less useful for experienced users who know to import things.
This is why the feature is not "auto-import anything", but "give Python code the chance to deal with NameError". Open to bikeshedding about whether it's better per-module or global or what, but the point is that you, as the programmer, get the flexibility. Maybe you want to white-list potential imports, which would make this like pre-importing those names but lazily. Maybe you want to allow a half-dozen common "from" imports, but not just anything. Maybe you'd like to have some completely different magic - like REXX mode:
import sys sys.__getglobal__ = lambda name: name.upper() foo = "Ham " foo + spam 'Ham SPAM'
Or something more suitable for floating point work:
sys.__getglobal__ = lambda name: float("nan") x = 4 x + y nan
The power is in your hands. And by default, nothing is any different: $ python3 Python 3.5.0a0 (default:1c51f1650c42+, Dec 29 2014, 02:29:06) [GCC 4.7.2] on linux Type "help", "copyright", "credits" or "license" for more information.
foo Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'foo' is not defined
Don't like auto-importing? Don't use it. That simple. :) Incidentally, I fully expect that the dunder name __getglobal__ will be rejected. But the proposal works equally well with any name. ChrisA