0

I am trying to import two interdependent classes called A and B located into a folder named 'static_classes', in order to call their static methods within my program.

A class code:

from b import B

class A:
    @staticmethod
    def a():
        print('a')
        B.b()

B class code:

import sys

if 'A' not in sys.modules:
    from a import A

class B:
    @staticmethod
    def b():
        print('b')
        A.a()

Main code:

import sys
sys.path.append('./static_classes')

from a import A
from b import B

A.a()
B.b()

However after running the program, I get a runtime error message saying:

ImportError: cannot import name B

I don't know why it's not possible to import the class B. What I'm missing?

user6039980
  • 3,108
  • 8
  • 31
  • 57
  • 1
    You cannot cyclic import! https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python – Nannan AV May 02 '18 at 14:48
  • Thanks for the link to the dupe @NannanAV. – Christian Dean May 02 '18 at 14:49
  • @NannanAV Can I pass the class `A` as parameter for the `b` method? – user6039980 May 02 '18 at 15:01
  • @Kais No, you cannot.! I strongly urge you to go through the above link in case you already haven't. What you might be able to do in this case is pass a variable x to the b method and call x.a() inside b. Assign x = A or A() before you want to call B.b(x). But I'm still not sure as to why you want to create an infinite loop! – Nannan AV May 02 '18 at 15:08

0 Answers0