Proposal: Inline Import
bokr at oz.net
Sun Dec 11 04:12:52 CET 2005
On Fri, 09 Dec 2005 12:24:59 -0700, Shane Hathaway <shane at hathawaymix.org> wrote:
>Here's a heretical idea.
>I'd like a way to import modules at the point where I need the
>functionality, rather than remember to import ahead of time. This might
>eliminate a step in my coding process. Currently, my process is I
>change code and later scan my changes to make matching changes to the
>import statements. The scan step is error prone and time consuming.
>By importing inline, I'd be able to change code without the extra scan step.
>Furthermore, I propose that the syntax for importing inline should be an
>expression containing a dot followed by an optionally dotted name. For
> name_expr = .re.compile('[a-zA-Z]+')
>The expression on the right causes "re.compile" to be imported before
>calling the compile function. It is similar to:
> from re import compile as __hidden_re_compile
> name_expr = __hidden_re_compile('[a-zA-Z]+')
>The example expression can be present in any module, regardless of
>whether the module imports the "re" module or assigns a different
>meaning to the names "re" or "compile".
>I also propose that inline import expressions should have no effect on
>local or global namespaces, nor should inline import be affected by
>local or global namespaces. If users want to affect a namespace, they
>must do so with additional syntax that explicitly assigns a name, such as:
> compile = .re.compile
Are you willing to type a one-letter prefix to your .re ? E.g.,
>>> class I(object):
... def __getattr__(self, attr):
... return __import__(attr)
>>> I = I()
>>> name_expr = I.re.compile('[a-zA-Z+]')
<_sre.SRE_Pattern object at 0x02EF4AC0>
>>> compile = I.re.compile
<function compile at 0x02EFE144>
>>> pi = I.math.pi
Of course it does cost you some overhead that you could avoid.
>In the interest of catching errors early, it would be useful for the
>Python parser to produce byte code that performs the actual import upon
>loading modules containing inline import expressions. This would catch
>misspelled module names early. If the module also caches the imported
>names in a dictionary, there would be no speed penalty for importing
>inline rather than importing at the top of the module.
>I believe this could help many aspects of the language:
>- The coding workflow will improve, as I mentioned.
>- Code will become more self-contained. Self-contained code is easier
>to move around or post as a recipe.
>- There will be less desire for new builtins, since modules will be just
>as accessible as builtins.
There are special caveats re imports in threads, but otherwise
I don't know of any significant downsides to importing at various
points of need in the code. The actual import is only done the first time,
so it's effectively just a lookup in sys.modules from there on.
Am I missing something?
More information about the Python-list