python 类型:将函数签名类型声明与函数定义分离

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

我想确保几个函数通过类型检查实现相同的接口。 我是怎么做到这一点的?我会为此使用额外的工具吗?
为了完整起见:我使用 mypy 作为类型检查器。

示例:

binaryFunction = Callable[[float, float], float]

def plus(a, b):
   return a + b

def minus(a, b):
    return a - b

如何指定

plus
minus
都遵守 binaryFunction 接口?

看起来有效的方法:

checkedPlus: binaryFunction = plus
checkedMinus: binaryFunction = minus

但这看起来很奇怪;我觉得这根本不是Pythonic,所以我会避免这样做,除非我确信这确实是实现这一目标的方法。

我在下面的答案中有一个可能的解决方案,但感觉还有改进的空间。

python typing
1个回答
0
投票

这似乎有效,但要么有点重复,要么有点分配

from typing import Callable

def binaryFunction(implementation: Callable[[float, float], float]) -> Callable[[float, float], float]:
    return implementation

# assign signature to name instead of repeating it's literal

_binaryFunctionSignature: Callable[[float, float], float])
def binaryFunction(implementation: _binaryFunctionSignature) -> _binaryFunctionSignature:
    return implementation

@binaryfunction
def decoratedPlus(a, b): 
    return a + b

decoratedPlus(1, 1j)  # fails type checking but runs - as expected

是这样吗?可以改进吗?

© www.soinside.com 2019 - 2024. All rights reserved.