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()
In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.
You can, however, use the imported module inside functions and code blocks that don't get run on import. Generally, in most valid cases of circular dependencies, it's possible to refactor or reorganize the code to prevent these errors and move module references inside a code block.
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
As explained in my answer, it is possible for modules to import each other, but if you need to do that, you may want to reconsider your design.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With