相关疑难解决方法(0)

为了类型检查而将NamedTuple子类化的方法

我有几个分享一些字段的命名元组.我有一个接受这些元组的函数,并保证只与共享字段交互.我想在mypy中检查这样的代码.

代码的一个例子是:

from typing import NamedTuple

class Base(NamedTuple):
    x: int
    y: int


class BaseExtended(NamedTuple):
    x: int
    y: int
    z: str

def DoSomething(tuple: Base):
    return tuple.x + tuple.y

base = Base(3, 4)
base_extended = BaseExtended(5, 6, 'foo')

DoSomething(base)
DoSomething(base_extended)
Run Code Online (Sandbox Code Playgroud)

当我在这段代码上运行mypy时,我得到一个可预测的错误:

mypy_example.py:20:错误:"DoSomething"的参数1具有不兼容的类型"BaseExtended"; 预期"基地"

有没有办法构建我的代码并保持mypy typechecking?我不能从Base继承BaseExtended,因为NamedTuple继承实现中存在一个错误:

https://github.com/python/typing/issues/427

我也不想使用一个丑陋的"Union [Base,BaseExtended]",因为当我尝试对一个List进行类型检查时会出现这种情况,因为"List [Union [Base,BaseExtended]]"不等于"List [BaseExtended] ]"由于关于变体/协变类型的一些mypy魔术:

https://github.com/python/mypy/issues/3351

我应该放弃这个想法吗?

python typing namedtuple mypy

13
推荐指数
1
解决办法
2367
查看次数

标签 统计

mypy ×1

namedtuple ×1

python ×1

typing ×1