python - 类型提示 : solve circular dependency

标签 python type-hinting python-typing

以下产生 NameError: name 'Client' is not defined。我该如何解决?

class Server():
    def register_client(self, client: Client)
        pass


class Client():
    def __init__(self, server: Server):
        server.register_client(self)

最佳答案

您可以使用 forward reference通过为尚未定义的 Client 类使用 string 名称:

class Server():
    def register_client(self, client: 'Client')
        pass

As of Python 3.7 ,您还可以通过在模块顶部添加以下 __future__ 导入来推迟注释的 all 运行时解析:

from __future__ import annotations

此时注释被存储为表达式的抽象语法树的字符串表示;您可以使用 typing.get_type_hints()解决这些问题(并解决上面使用的前向引用)。

PEP 563 -- Postponed Evaluation of Annotations详情;此行为将是 Python 4.0 中的默认行为。

关于python - 类型提示 : solve circular dependency,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33837918/

相关文章:

python - 使用 pcapy 或 scapy 监控自生(HTTP)网络流量

python - 如何使用 SQLAlchemy 在插入时解析相关的外键?

python - 适用于桉树云的 boto 版本

python - 相同类型的多个参数的类型提示?

python - 在 FastAPI 中使用 Annotated 会忽略 Query 中设置的规则

python - 如何键入使用默认值动态创建的枚举?

Python swig - 从 ctypes 指针创建 swig 包装实例

python - Typehint 使用 importlib 动态导入模块

python - 使用 Python 类型模块指定序列或列表的长度

python - python中类继承Generic的目的是什么?