【问题标题】:Nested TypeDict defined as inner class嵌套的 TypeDict 定义为内部类
【发布时间】:2022-10-13 01:29:10
【问题描述】:

我正在尝试将“嵌套”TypedDict 定义为一组内部类,其中SomeDict 字典应该有一个id 字段,该字段可以是另一个TypedDictNone

from typing import TypedDict

class MyClass:

    class SomeIdFieldDict(TypedDict):
        some_nested_field: str

    class SomeDict(TypedDict):
        id: SomeIdFieldDict | None # The error is in this line.

上面的代码给了我以下错误:NameError: name 'SomeIdFieldDict' is not defined

我尝试引用 SomeIdFieldDict,但现在 Python 类型检查器将其视为字符串:

from typing import TypedDict

class MyClass:

    class SomeIdFieldDict(TypedDict):
        some_nested_field: str

    class SomeDict(TypedDict):
        id: "SomeIdFieldDict" | None # The error is in this line.

有了以上内容,我得到:

TypeError: unsupported operand type(s) for |: 'str' and 'NoneType'

我也尝试过引用顶级类,但无济于事(得到与上面相同的错误):

from typing import TypedDict

class MyClass:

    class SomeIdFieldDict(TypedDict):
        some_nested_field: str

    class SomeDict(TypedDict):
        id: "MyClass.SomeIdFieldDict" | None # The error is in this line.

我尝试采用的另一种方法是定义id 类型“内联”,如下所示:

from typing import TypedDict

class MyClass:

    class SomeDict(TypedDict):
        id: TypedDict("SomeIdFieldDict", {"some_nested_field": str}) | None

...但似乎没有正确解析,并且该字段被视为Anyid 字段的类型提示显示为:id: Any | None

有什么方法可以将这种“嵌套”TypeDict 定义为内部类?

【问题讨论】:

    标签: python typeddict


    【解决方案1】:

    您可以改用typing.Optional["SomeIdFieldDict"],或者我建议您使用__future__.annotations,如下所示:

    from __future__ import annotations
    from typing import TypedDict
    
    
    class MyClass:
        class SomeIdFieldDict(TypedDict):
            some_nested_field: str
    
        class SomeDict(TypedDict):
            id: SomeIdFieldDict | None
    
    
    def f(x: MyClass.SomeDict) -> None:
        print(x)
    
    
    if __name__ == '__main__':
        f({"id": {"some_nested_field": "a"}})  # works
        f({"foo": "bar"})  # error: Extra key "foo" for TypedDict "SomeDict"
    

    这将按预期通过/失败mypy。但是,我注意到 PyCharm 仍然错误地抱怨 Unresolved reference 'SomeIdFieldDict'。但这是他们的一个错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-05
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2015-10-21
      • 1970-01-01
      相关资源
      最近更新 更多