如何输入带有别名的提示函数

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

我想输入提示一些具有给定别名的函数,但我看不到明显干净的方法来执行此操作。例如,与

Foo = Callable[[int], str]


def foo1(x: int) -> str:
    ...


def foo2(x: int) -> str:
    ...

很容易看出它们都是

Foo
,但我的函数具有更复杂的签名,并且用眼睛检查它们很烦人并且容易出错。

我正在寻找像这样的 idris 代码

Foo : Type
Foo = Int -> String

foo1 : Foo
foo1 x = ?rhs

foo2 : Foo
foo2 x = ?rhs

这里很明显什么是

Foo
,如果我有
Int -> String
但不是故意
Foo
的函数,那就很清楚了。

一种方法是

Foo = Callable[[int], str]


def _foo1(x: int) -> str:
    ...

foo1 : Foo = _foo1

但我想找到一些更自然地与文档一起工作并且不需要(某种)重复的东西。

python type-hinting
1个回答
0
投票

我的函数具有更复杂的签名,用眼睛检查它们很烦人并且容易出错。

如果我有

int -> str
但不是故意
Foo
的功能,那就很清楚了。

考虑到这两点,很明显这是为了帮助人类,而不是类型检查器。
记住这一点,在 PyCharm 中看起来不错(至少在屏幕上显示类型别名,尽管作为装饰器参数)并且不会触发 WPS linter 的解决方案如下:

# turns a two-argument function
# that accepts our function as *second* argument
# and returns it without any changes at runtime
# into a no-runtime-overhead decorator factory
annotate = partial(partial, cast)  # from typing import cast

Foo = Callable[[int], str]

@annotate(Foo)
def foo1(x: int) -> str:
    ...

@annotate(Foo)
def foo2(x: int) -> str:
    ...

@annotate(Foo)
行显示在将鼠标悬停在
foo1
foo2
函数上时显示的 PyCharm 工具提示中。甚至文档字符串也不会丢失(如果有)!

可悲的是,以下...

@annotate(Foo)
def foo(x):
    ...

...不会告诉 PyCharm

foo
的返回值和
x
参数的类型,但此解决方法既不打算也不期望这样做。

附注不确定

annotate
是否是这个装饰器的最佳名称,但这显然是尝试注释函数变量,所以...
我考虑过
mark_as
with_alias
,但这些不太可能促使(或通过指导)某人通过阅读他人的代码来学习 Python 进行额外的研究。

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