小编Nea*_*tan的帖子

类型检查返回类 PEP 484

我在 python 中有一个函数,它返回一个类而不是一个实例。如何指示返回值是特定类型的子类?

在下面的示例中,我将返回值设置为类型,但我想进一步指出该类型具有 BaseClass 的所有属性:

from typing import Dict, Any

def class_constructor(name: str, attrs: Dict[str, Any]) -> type
    ConstructedClass = type(name, (BaseClass,), attrs)
    return ConstructedClass

class BaseClass: ...
Run Code Online (Sandbox Code Playgroud)

我不能说 (...) -> BaseClass,因为这表示 BaseClass 的实例而不是 BaseClass 本身。

为了回答我自己的问题,这显示为python/typing issue #107。目前,最好的解决方案是:

from typing import Dict, Any

class BaseClass: ...

def class_constructor(name: str, attrs: Dict[str, Any]) -> Callable[Any, BaseClass]
    ConstructedClass = type(name, (BaseClass,), attrs)
    return ConstructedClass
Run Code Online (Sandbox Code Playgroud)

如果你知道你的__init__签名,你可以使用它而不是Anyin Callable[Any, ...]

Type[T]添加对 的支持后,解决方案将是:

 from typing import …
Run Code Online (Sandbox Code Playgroud)

python typing type-hinting

5
推荐指数
1
解决办法
326
查看次数

标签 统计

python ×1

type-hinting ×1

typing ×1