是否可以更改 `typing.TypedDict` 的字符串表示形式?

Is it possible to change string representation of a `typing.TypedDict`?

我可以在从本机 dict 进行子类化时做到这一点,但不能使用键入的版本。这是代码:

from typing import TypedDict


class Typed(TypedDict):
    x: int

    def __str__(self):
        return "str-typed"


class Native(dict):
    def __str__(self):
        return "str-native"


typed = Typed(x=1)
print("typed =", typed)

native = Native(x=1)
print("native =", native)

assert typed == native

及其结果:

$ python typed_dict.py 
typed = {'x': 1}
native = str-native

$ mypy typed_dict.py 
typed_dict.py:7: error: Invalid statement in TypedDict definition; expected "field_name: field_type"
Found 1 error in 1 file (checked 1 source file)

有什么建议吗?

调用 Typed 创建一个普通的字典。您编写的方法不会执行任何操作,因为 typed 不是 Typed 的实例并且没有任何 Typed 的方法。

虽然技术上可以在运行时禁用该行为(在当前的 3.8 实现中,del Typed.__new__ 会这样做),但 mypy 仍然不会高兴。 TypedDict 的意图是

class Foo(typing.TypedDict):
    x: int
    y: str

d: Foo = {'x': 1, 'y': 'blah'}

类型检查。 TypedDict 子类旨在表示具有特定字符串键的 常规字典 的静态类型。它不应该用作自己单独的运行时类型。

此外,del Typed.__new__ 会深入研究实施细节,如有更改,恕不另行通知。