Search code examples
pythongame-engine

How to avoid circular import looping


I am getting confused with importing in python. It seems that I have the problem of circular importing, but I am not sure how to fix this problem in the right way. An example:

file1:

value = 5

import file2
file2.set()

file2:

import file1

def set():
    file1.value = 6

Solution

  • You have a few options:

    1. put all your code in one file, if it needs to be this tightly linked
    value = 5
    
    def set():
        value = 6
    
    set()
    
    1. put the code that uses parts from the others in a third file, or in other words break up your code so you avoid the circular references - your example is a bit too simple to make that work though.

    2. pass values to functions you want to use, or pass objects you want to modify; importing and modifying another module's globals isn't a very good way to design your program anyway:

    # this is my_module.py
    
    def set_value(x):
        x.value = 6
    
    
    def increment(x):
        return x + 1
    

    And elsewhere:

    import my_module
    
    
    class X:
        value = 5
    
    
    x = X()
    my_module.set_value(x)
    
    y = 5
    y = my_module.increment(y)