Python 中可调用对象的新类型

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

我想定义两种类型

Shape
Square
。这里
Square
Shape
的子类。

Shape = NewType('Shape', tuple[int, int])
Square = NewType('Square', Shape)

def square_area(sh: Square) -> int:
    a, b = sh
    return a * b

def shape_area(sh: Shape) -> int:
    a, b = sh
    return a * b

我将定义一个附加类型

SquareCalculator
,如下所示:

SquareCalculator = NewType('Calculator', Callable[[Square], int])

def get_calc() -> SquareCalculator:
    return square_area

上面的代码导致mypy中出现以下错误:

newtyp.py:10: error: String argument 1 "Calculator" to NewType(...) does not match variable name "SquareCalculator"
newtyp.py:13: error: Incompatible return value type (got "Callable[[Square], int]", expected "SquareCalculator")
Found 2 errors in 1 file (checked 1 source file)

有办法解决这个问题吗?请注意,我想保持

Shape
Square
之间的差异,以确保类型检查在它们互换时捕获错误。

python python-typing mypy
1个回答
2
投票

SquareCalculator
应该是类型别名,而不是新类型,否则需要使用
typing.cast

当前语法:

from typing import TypeAlias
from collections.abc import Callable

SquareCalculator: TypeAlias = Callable[[Square], int]

Python 3.12 语法:

from collections.abc import Callable

type SquareCalculator = Callable[[Square], int]
© www.soinside.com 2019 - 2024. All rights reserved.