Python usually doesn’t have strict type definitions, but if it’s a common, fixed data structure, it’s easier to define it clearly (or at least type after the object). The IDE can automatically prompt method and property names. In this case, it is possible to refer to a complex structure in a circular manner, such as:
from typing import List
class A:
x: str
y: B
class B:
w: List[A]
Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B: Unresolved reference B There are two solutions:
- Keep the classes defined in the same file
You can add a special reference at this point:from __future__ import annotations
, telling the compiler to “read through” the entire file before processing the typing annotation can avoid the above problem. - In this case, we need to refer to another class by referring to its module, not the class name:
Module1.py
from . import Module2
class A:
x: str
y: Module2.B
Module2.py
from typing import List
from . import Module1
class B:
w: List[Module1.A]