Python:类型标注解决循环引用问题most likely due to a circular import

两个模块,我们需要做类型标注,于是出现了循环引用的问题

# models.py
from controllers import BookController


class Book:
    def get_controller(self) -> BookController:
        return BookController(self)

# 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

# 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

# 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

参考文章

  • Python Type Hints - How to Fix Circular Imports

你可能感兴趣的:(Python,python,开发语言)