Cannot Import Name: Solution to Circular Dependency (Python)

May 27, 2019

Example of Circular Dependency

test_circular.py

from main import NAME

def printName():
    print(NAME)

main.py

NAME = 'Hello'

from test_circular import print_name

if __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_name

if __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 NAME

def print_name():
    print(NAME)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.