[Python-ideas] Implicit submodule imports

Nick Coghlan ncoghlan at gmail.com
Fri Sep 26 11:43:03 CEST 2014


On 26 September 2014 18:44, Chris Angelico <rosuav at gmail.com> wrote:
> On Fri, Sep 26, 2014 at 6:15 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> By making importing automatic, every failed attribute access has to
>> determine whether or not there is a sub-module to import, which could be
>> quite expensive.
>
> What if the package had to explicitly do a "stub import" that creates
> something that, on first access (or first access of any of *its*
> members), goes and loads up the module?

It's also worth noting the caution in
https://docs.python.org/dev/library/importlib.html#importlib.util.LazyLoader

Yes, the AttributeError when you try to access a submodule that hasn't
been imported yet can be a little confusing, but it's positively
crystal clear compared to the confusion you encounter when an
attribute access attempt fails with ImportError (or, worse, if the
AttributeError is hiding an import error).

Explicit, eager imports make it clear when module level code execution
might be triggered, with all the associated potential for failure
(whether in module lookup, in compilation, in bytecode caching or in
code execution).

Implicit and lazy imports take that complexity, and run it
automatically as part of a __getattr__ operation. There are valid
reasons for doing that (such as to improve startup time in large
applications), but postponing the point where new users need to learn
the difference between "package attribute set in __init__" and
"imported submodule" likely isn't one of them.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list