Optional typing in python: problems with imports

Question:

I am writing in python 3.5, trying to use typing, but faced the problem of circular import – it became difficult to split the program into modules.

One of the problems with the one-to-one relationship:

# модуль 1
from mod1 import B

class A:
    def __init__(self):
        self.__B = B(self)

# модуль 2
from mod2 import A

class B:
    def __init__(self, arg: A):
        self.__a = arg

And so on. The problem grows seriously with the increase in the number of modules.

I want to know if I am approaching the problem incorrectly, or is there a solution to the problem?

PS: I'm in the sense that an ImportError is thrown and I can't get rid of it.

Answer:

PEP 484 – Type Hints recommends using import module instead of from module import Type and specifying types as strings to mitigate the effects of circular dependency caused by using type hints:

# mod1.py
import mod2

class B:
    def __init__(self, arg: 'mod2.A') -> None:
        self.__a = arg
# mod2.py
import mod1

class A:    
    def __init__(self):
        self.__b = mod1.B(self)

Alternatively, if the classes are so closely related, you can put them in one module or perform another refactoring appropriate for the case (perhaps a more general type, defined, for example, in mod2.types , should be used in B ). See Type hinting would generate a lot of import statements (possibly leading to circular imports). Use strings instead of imported names?

Scroll to Top