[Python-ideas] ImportError raised for a circular import

Mahmoud Hashemi mahmoud at hatnote.com
Tue Jun 13 18:49:54 EDT 2017


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. :)

My only problem with it is that it makes people look at "a.py". And if you
look at "a.py", you'll see there's a "q" there. While most of us on this
list will check for the circular import, it's quite a bit of headscratching
as to why Python can't find the "q", when it's right there in the file.
Calling out the circular import possibility explicitly makes people look at
the _whole_ stack track, and even if real stack traces are quite a bit
longer, they'll probably make the connection.

The AttributeError idea is definitely interesting because it's also a major
player in circular import confusions. I think it's an ambitious idea, and
would be very exciting if it were implemented.

On Tue, Jun 13, 2017 at 3:36 PM, Chris Angelico <rosuav at gmail.com> wrote:

> On Wed, Jun 14, 2017 at 8:10 AM, Mahmoud Hashemi <mahmoud at hatnote.com>
> wrote:
> > I didn't interpret the initial email as wanting an error on *all*
> circular
> > imports. Merely those which are unresolvable. I've definitely helped
> people
> > diagnose circular imports and wished there was an error that called that
> out
> > programmatically, even if it's just a string admonition to check for
> > circular imports, appended to the ImportError message.
>
> Oh! That could be interesting. How about a traceback in the import chain?
>
> # a.py
> import b
> q = 1
>
> # b.py
> import c
>
> # c.py
> from a import q
>
> c.py will trigger an ImportError, but that could say something like... oh
> look:
>
> $ python3 a.py
> Traceback (most recent call last):
>   File "a.py", line 1, in <module>
>     import b
>   File "/home/rosuav/tmp/asdf/b.py", line 1, in <module>
>     import c
>   File "/home/rosuav/tmp/asdf/c.py", line 1, in <module>
>     from a import q
> ImportError: cannot import name 'q' from 'a' (/home/rosuav/tmp/asdf/a.py)
>
> Already happens :)
>
> A bit harder, but also possible, would be to have an AttributeError on
> a module recognize that an import is happening, and report a possible
> circular import. That'd take some engineering, but it would be
> helpful. That'd catch cases like:
>
> # c.py
> import a
> print(a.q)
>
> Is that what you're looking for?
>
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170613/e3a5bd7e/attachment.html>


More information about the Python-ideas mailing list