How to Break Import Loop in python

Question:

I have a situation where there two related large python classes and hence i have put them in separate files. Let say classes are Cobra and Rat.

Now need to call methods of Rat from methods of Cobra and vice versa.
For this i need to import Cobra in Rat.py and Rat in Cobra.py

This creates an import loop and gives an error. Cant import Cobra inside Cobra.

How to fix this??

Cobra.py:

import Rat
class Cobra():
    def check_prey(self, rat ):
        # Some logic 
        rat.foo()

Rat.py:

import Cobra
class Rat():
    def check_predator(self, snake ):
        # some_logic ..
        snake.foo()
Asked By: Tiwari

||

Answers:

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.

Answered By: Charles Ma
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.