两个模块,我们需要做类型标注,于是出现了循环引用的问题
python
# models.py
from controllers import BookController
class Book:
def get_controller(self) -> BookController:
return BookController(self)
python
# controllers.py
from models import Book
class BookController:
def __init__(self, book: Book) -> None:
self.book = book
这两个文件相互引用了,实际上我们仅用于类型标注
most likely due to a circular import
解决办法
使用 TYPE_CHECKING
python
# controllers.py
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from models import Book
class BookController:
def __init__(self, book: "Book") -> None:
self.book = book
或者使用 annotations + TYPE_CHECKING
python
# controllers.py
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from models import Book
class BookController:
def __init__(self, book: Book) -> None:
self.book = book