How to Break Import Loop in python

前端 未结 1 1469
面向向阳花
面向向阳花 2020-12-24 06:42

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 met

相关标签:
1条回答
  • 2020-12-24 07:29

    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.

    0 讨论(0)
提交回复
热议问题