Better error message on recursive import
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Fri Sep 12 05:27:39 EDT 2008
On Fri, 12 Sep 2008 09:47:42 +0200, Thomas Guettler wrote:
>> Can you give an example of such a recursive import you want the special
>> exception be raised?
>
> ===> cat one.py
> from two import testtwo
> def testone():
> print "one"
>
> ===> cat two.py
> import one
> def testtwo():
> print "two"
>
> ===> python one.py
> Traceback (most recent call last):
> File "one.py", line 1, in <module>
> from two import testtwo
> File "/mnt/home/tguettler/tmp/rec/two.py", line 1, in <module>
> import one
> File "/mnt/home/tguettler/tmp/rec/one.py", line 1, in <module>
> from two import testtwo
> ImportError: cannot import name testtwo
This is an awkward situation anyway because here are *three* modules
involved. You start `one.py` which will be imported as `__main__`.
`__main__` imports `two` and `two` imports a *new* module `one`! Which
tries to import `testtwo` from `two` which doesn't exist at that time.
Even if you rearrange the code to load properly `one.py` is loaded and
executed *twice* and you end up with two distinct modules generated from
that file.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list