如何让 python 类型检查器知道它应该 return 它的 class 的新实例?

How to let python type checker know that it should return a new instance of its class?

我想使用 class 方法来 return 当前 class 的新实例,我已经尝试了如下代码,但它引发了 NameError('name 'T' 未定义')

将代码 T = TypeVar('T', bound=A) 放在上面的 class A 上也不起作用。

有什么好的处理方法吗?

import json
from typing import TypeVar


class A(dict):

    def __init__(self, name):
        super(dict, self).__init__()
        self["name"] = name


    @classmethod
    def foo(cls: T, args: str)->T:
        return json.loads(args)
T = TypeVar('T', bound=A)


class B(A):
    pass

b = B(name='B')
# True
print(isinstance(b.foo(json.dumps(b)),B))

使用字符串对A进行前向引用并给cls正确的类型Type[T]:

import json
from typing import Type, TypeVar


T = TypeVar('T', bound='A')


class A(dict):
    def __init__(self, name: str) -> None:
        super().__init__(name=name)

    @classmethod
    def foo(cls: Type[T], args: str) -> T:
        return cls(**json.loads(args))


class B(A):
    def is_b(self) -> bool:
        return True


b = B.foo('{"name": "foo"}')
print(b.is_b())