Cannot Import Name: Solution to Circular Dependency (Python)

May 27, 2019

Example of Circular Dependency

test_circular.py

from main import NAMEdef printName():    print(NAME)

main.py

NAME = 'Hello'from test_circular import print_nameif __name__ == '__main__':    print_name()

Test

python main.py
ImportError: cannot import name 'print_name' from 'test_circular' (/test_circular.py)

The problem is resolved then dependency on main is removed from test_circular.py.

Solution 1

Edit test_circular.py

def print_name():    from main import NAME    print(NAME)

Solution 2

Edit main.py

NAME = 'Hello'from test_circular import *if __name__ == '__main__':    print_name()

NOTE: Downside is importing everything from test_circular.py

Solution 3

Edit main.py

NAME = 'Hello'import test_circular# This would not work# print_name = test_circular.print_nameif __name__ == '__main__':    print_name = test_circular.print_name    print_name()

Solution 4

Move NAME = 'Hello' into settings.py

Edit test_circular.py

from settings import NAMEdef print_name():    print(NAME)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.