pythonpython-importpython-typingcircular-dependency

Circular imports and annotations


If I want to use annotations in both classes in the different modules is cross?

from BModule import B

class A:
  def method(self, b: B):
     pass

~

from AModule import A

class B:
  def method(self, a: A):
     pass

I got a ImportError: cannot import name 'B'? But how if I need annotate this, what to do?

Also if I just import AModule\BModule and use class as attribute of module AModule.A I got AttributeError: module 'BModule' has no attribute 'B'


Solution

  • What is forcing the dependency? It seems to me that in this case, any method of A that takes a B could be implemented as a method on B that takes an A, so make one of the classes the "main" class and use that class to operate on objects of the other class, if that makes sense?