动态创建类的动态类型提示

问题描述 投票:0回答:0

我想为动态创建的类创建类型提示。我有以下代码,但它不适用于类型提示。

from typing import Type, cast, Unpack, Annotated, TypedDict, Callable

class Base:
    def __init__(self, **kwargs: object) -> None:
        pass

def create() -> Type[Base]:
    class TD(TypedDict):
        first: int
        second: str
    def __init__(self, **kwargs: Unpack[TD]):
        setattr(self, 'a', kwargs['first'])
        setattr(self, 'b', kwargs['second'])

    __init__.__annotations__.update({'kwargs': Unpack[TD]})

    return type('Child', (Base,), {'__init__': __init__, '__annotations__': {'a': int, 'b': str}})

Child = create()

c = Child(first=1, second='Hello')
print(c.b) # 'Hello'

print(Child.__annotations__) # {'a': int, 'b': str}
print(Child.__init__.__annotations__['kwargs'].__args__[0].__annotations__) # {'first': int, 'second': str}

我错过了什么还是这根本不可能?

python type-hinting
© www.soinside.com 2019 - 2024. All rights reserved.