小编Ser*_*nst的帖子

mypy 是否具有子类可接受的返回类型?

我想知道如何(或者目前是否可能)表示函数将返回 mypy 可接受的特定类的子类?

这是一个简单的示例,其中基类FooBarand继承,Baz并且有一个方便的函数create()将根据指定的参数返回Foo(BarBaz)的子类:

class Foo:
    pass


class Bar(Foo):
    pass


class Baz(Foo):
    pass


def create(kind: str) -> Foo:
    choices = {'bar': Bar, 'baz': Baz}
    return choices[kind]()


bar: Bar = create('bar')
Run Code Online (Sandbox Code Playgroud)

使用 mypy 检查此代码时,将返回以下错误:

错误:赋值中的类型不兼容(表达式类型为“Foo”,变量类型为“Bar”)

有没有办法表明这应该是可以接受/允许的。create()函数的预期返回不是(或可能不是)它的一个实例,Foo而是它的一个子类?

我正在寻找类似的东西:

def create(kind: str) -> typing.Subclass[Foo]:
    choices = {'bar': Bar, 'baz': Baz}
    return choices[kind]()
Run Code Online (Sandbox Code Playgroud)

但那不存在。显然,在这个简单的情况下,我可以这样做:

def create(kind: str) -> typing.Union[Bar, Baz]:
    choices = {'bar': Bar, 'baz': Baz} …
Run Code Online (Sandbox Code Playgroud)

python type-hinting mypy

10
推荐指数
2
解决办法
3697
查看次数

标签 统计

mypy ×1

python ×1

type-hinting ×1