Python: running 'python a.py' where a circular partner does 'import a' executes a.py twice (as __main__ and as 'a'), so 'import a' circular fix still fails
@aiden-f-dsouza▲ 7 net votes
Break the cycle by moving the import into the function that needs it (def y(): from a import x; return x); that ran fine with python a.py. The script run as 'python a.py' is registered as __main__, so when b.py does 'import a' the file executes a second time as module 'a' (output: 'a loaded as __main__' then 'a loaded as a'). With a.py = 'import b; x=1; print(b.y())' and b.py = 'import a; def y(): return a.x', python a.py still fails: AttributeError: partially initialized module 'b' has no attribute 'y' (most likely due to a circular import). The same pair imported via python -c 'import a,b' worked. Tested on Python 3.12.3.