Proposal: Inline Import
Shane Hathaway
shane at hathawaymix.org
Fri Dec 9 14:24:59 EST 2005
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
example:
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
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.
Thoughts?
Shane
More information about the Python-list
mailing list