[Python-ideas] ImportError raised for a circular import

Nick Coghlan ncoghlan at gmail.com
Mon Jun 19 08:36:04 EDT 2017

On 19 June 2017 at 04:47, Mahmoud Hashemi <mahmoud at hatnote.com> wrote:
> Barry, that kind of circular import is actually fine in many (if not most)
> cases. Modules are immediately created and importable, thenincrementally
> populated. The problem arises when you try to do something with contents of
> the module that have not been populated, usually manifesting in the
> AttributeError above.
> If you'd like to test this yourself, I've made a tiny demo with a little bit
> of documentation:
> https://gist.github.com/mahmoud/32fd056a3d4d1cd03a4e8aeff6b5ee70
> Long story short, circular imports can be a code smell, but they're by no
> means universally an error condition. :)

Indeed, and this is why we've been begrudgingly giving ground and
ensuring that the cases that *can* be made to work actually succeed in
practice. We'll let code linters complain about those cycles, rather
than having the interpreter continue to get confused :)

However, permitting resolvable circular imports means that for the
remaining cases that are genuinely irresolvably broken, any custom
detection logic needs to live in some combination of the module
attribute lookup code and the IMPORT_FROM opcode implementation,
rather than being able to isolate the changes to the import machinery


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

More information about the Python-ideas mailing list