You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The from...import section of the Python style guide says:
Rationale: This is the single best -- and easiest -- way to avoid the circular-import problem. To simplify, when you say import x, Python executes the x.py file, but doesn't need to get any attributes from it. When you say from x import foo, Python needs x.py to be executed enough that foo is defined in it. When x does a 'from-import' from y, and y does a 'from-import' from x, the circular import can succeed if a partial module is enough (as it will be with import x), but it can fail if the circularity happens before the needed attribute is defined (as it might be with from x import foo).
I had trouble proving this to myself with manual testing; I think this section could really benefit from a link to some concrete example code that showcases a successful example of this behavior.
The text was updated successfully, but these errors were encountered:
>>> import a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "a.py", line 1, in <module>
from b import b_test
File "b.py", line 1, in <module>
from a import a_test
ImportError: cannot import name a_test
Instead, if I do what the style guide suggests:
# a.pyimportbdefa_test():
return1
# b.pyimportadefb_test():
returna.a_test()
then import a works fine, as does import b; b.b_test(). Since the first way is trying to access properties of the module before it has been defined, it fails. The second way just imports the modules and uses the properties later.
The from...import section of the Python style guide says:
I had trouble proving this to myself with manual testing; I think this section could really benefit from a link to some concrete example code that showcases a successful example of this behavior.
The text was updated successfully, but these errors were encountered: