0

I my Python Pyramid files, File2.py is importing File1.py and File1.py is importing File2.py, which is creating an infinite loop and raising Import error. I need to import these to use the public varibles of the classes as well as therir functions. How do i achieve this ?

I tried below :

File2.py
Class File2 :

    def __init__(self, sessionId):
        from server.eventmanager.file1 import File1 # : Doesnt Work
   if __name__ == "__main__":
      from server.eventmanager.file2 import File2 # : Doesnt Work(Tried both(init+ main)/either

    def myFunc(self):
        print(File1.myvar)



File1.py        
from /server/modules/mymodule/file2 import File2

Class File1:
    def __init__(self):
        pass

    myvar = False

    def updateMyVar(self,updatedvar):
        cls.myvar=updatedvar
        #Do Something

File "/server/eventmanager/file1.py", line 7, in <module>
from server.modules.mymodule.File2 import file2
File "/server/modules/mymodule/file2.py", line 13, in <module>
from server.eventmanager.File1 import file1
ImportError: cannot import name 'file1'
  • 2
    Possible duplicate of [Circular dependency in Python](https://stackoverflow.com/questions/894864/circular-dependency-in-python) https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python – prashant Aug 09 '19 at 10:39
  • How to reolve cyclic dependency https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python – prashant Aug 09 '19 at 10:40

2 Answers2

1

I think you are looking for cyclic dependency in python

Circular dependency in Pythonenter link description here

you can have look how to resolve them.

prashant
  • 2,808
  • 5
  • 26
  • 41
0

You can add above your first import an if clause.
If I understood you right then you start your code with File2.py.

In this case you should do it like that:

if __name__ == "__main__":
    import file1

If you run File2.py __name__ will be __main__. As a result the if - clause is true and you import File1.py. Well now File1.py imports File2.py but this time __name__ isn't __main__ because it doesn't run as a "main-file". This time __name__ will be File1 and File1 doesn't import Test2 anymore because the if clause stops it, but it still has the code of it because it already imported it one time.

Edit: Ok I got it! You have to put the if __name__ == "__main__" clause at the top of your code in your File1.py:

if __name__ == "__main__":
    from server.eventmanager.file2  import file2  # Doesnt Work(Tried both(init+ main)/either
    from server.eventmanager.file1 import File1  # : Doesnt Work

class File2:

    def __init__(self, sessionId):
        pass

    def myFunc(self):
        print(File1.myvar)
Soroush Chehresa
  • 5,490
  • 1
  • 14
  • 29
TornaxO7
  • 1,150
  • 9
  • 24