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

2024-01-07 23:10:36

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

# 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

参考文章

文章来源:https://blog.csdn.net/mouday/article/details/135435793
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。