How to Break Import Loop in python

If you don’t use Cobra in the class definition of Rat or vice versa (i.e. only used inside methods), then you can actually move the import statement to the bottom of the file, by which time the class definition would already exist.

# Cobra.py
class Cobra:
    # ...
    def check_prey(self, rat):
        # some logic
        rat.foo()
    
import Rat
# Rat.py
import Cobra
class Rat:
    # ...
    def check_predator(self, snake):
       # some_logic ..
       snake.foo()

Or you can limit the scope of the import:

# Cobra.py
class Cobra:
    # ...
    def check_prey(self, rat):
        import Rat
        # some logic
        rat.foo()
# Rat.py
import Cobra
class Rat:
    # ...
    def check_predator(self, snake):
       # some_logic ..
       snake.foo()

If you don’t use the Rat and Cobra class names directly, then you don’t even need the import statements at all: as long as the properties and functions exist in the rat or snake instances, Python doesn’t care what class they’re from.

In general, there is no foolproof way to avoid import loops. The best you can do is refactor your code and do some of the things I mentioned above.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)