[Python-ideas] ImportError raised for a circular import

Nick Coghlan ncoghlan at gmail.com
Tue Jun 13 22:41:13 EDT 2017


On 14 June 2017 at 08:49, Mahmoud Hashemi <mahmoud at hatnote.com> wrote:
> Oh I know the traceback, I've had many brought to my desk by a confused
> junior dev, looking a lot like yours truly a few years back. :)

Something worth noting is that as of 3.7, all circular imports that
actually *are* resolvable at runtime will be resolved:
https://bugs.python.org/issue30024

However, that only impacts submodules where the submodule entry exists
in sys.modules, but the name hasn't been bound in the parent module
yet - it doesn't help with module level attributes that would be
defined eventually, but we're still too early in the module's import
process for them to exist yet.

As Chris pointed out, there are two key points of name resolution to
take into account for those cases:

* ModuleType.__getattr__ ("import a; a.q")
* from_list processing in the import system ("from a import q")

Since the import system already keeps track of "currently in progress
imports" to manage the per-module import locks, both of those could
potentially be updated to query _frozen_importlib._module_locks to
find out if the source module was currently in the process of being
imported and raise a new CircularImportError that inherited from both
AttributeError and ImportError when that was the case.

Cheers,
Nick.

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


More information about the Python-ideas mailing list