查找适当的Python类型提示,例如内置函数map()的签名 [英] Finding the proper Python type hint, for instance, the signature of the built-in function map()

查看:80
本文介绍了查找适当的Python类型提示,例如内置函数map()的签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3.5或更高版本中,支持类型提示(请参见此处想要查询更多的信息).但是,没有充分记录常见类型的正确用法.

In Python 3.5 or above, type hints are supported (see here for more information). However, the proper usage for common types are not well documented.

例如,在官方网站上,我可以收集以下(正确的)用法:

For instance, from the official site, I could gather the following (proper) usages:

字符串

# The function signature of greeting is: Callable[[str], str]
def greeting(name: str) -> str:
    return 'Hello ' + name

整数

# The function signature of add is: Callable[[int, int], int]
def add(a: int, b: int) -> int:
    return a + b

浮点数

# The default value of x is 1.0
def reciprocal(x: float = 1.0) -> float:
    from math import nan
    if x == 0:
        return nan
    return 1 / x

列表

from typing import List, TypeVar

T = TypeVar('T')

def repeat(x: T, n: int) -> List[T]:
    return [x] * n

元组

from typing import Tuple, TypeVar

T = TypeVar('T')

def double(x: T) -> Tuple[T, T]:
    return (x, x)

问题

我的问题是:

1. map 的返回类型是什么?

1. What is the return type of map?

from typing import Iterable

# Is this correct?
x: Iterable[float] = map(int.__float__, [1, 2, 3])

我不确定这是否是上述 x 的正确类型提示.

I am not sure if this is the correct type hint for x above.

2.从广义上讲, map 的功能签名"是什么?

2. In a broader sense, what is the 'function signature' of map?

from typing import Callable, Iterable, TypeVar

T = TypeVar('T')
U = TypeVar('U')

# In the above usage, the type of the map function seems to be:
Function1 = Callable[[T], U]
typeOfMap = Callable[[Function1, Iterable[T]], Iterable[U]]

# Or in one line:
typeOfMap = Callable[[Callable[[T], U], Iterable[T]], Iterable[U]]

但是实际上,map函数可以接受多个可迭代对象.它被记录为:

But in fact, the map function can accept multiple iterables. It is documented as:

map(函数,可迭代,...)

它可以这样使用:

# The result is: [['A'], ['B', 'B'], ['C', 'C', 'C']]
result = list(map(repeat, ['A', 'B', 'C'], [1, 2, 3]))

T1 = TypeVar('T1')
T2 = TypeVar('T2')
R = TypeVar('R')

# So, the type of map function in this usage seems to be:
Function2 = Callable[[T1, T2], R]
typeOfMap = Callable[[Function2, Iterable[T1], Iterable[T2]], Iterable[R]]

总的来说,我想应该是下面的样子,但这不是正确的写法:

In general, I guess it should be something like below, but this is not the correct way to write it:

FunctionN = Callable[[T1, T2, ..., Tn], R]
typeOfMap = Callable[[FunctionN, Iterable[T1], Iterable[T2], ..., Iterable[Tn]], Iterable[R]]

那么,正确的书写方式是什么?

So, what is the correct way to write it?

3.通常,在哪里可以找到Python函数/方法的正确类型提示,包括内置函数,核心库中的内置函数?

主要出于学习目的,我需要它们.

I need them mainly for learning purpose.

4.有没有办法像Haskell或Erlang那样输出由编译器/解释器计算出的类型推断结果?

我知道Haskell和Erlang是函数式编程语言,并且变量是不可变的,因此使之成为可能会容易得多,但是如果我想知道Python也具有类似的功能,那么

I know Haskell and Erlang are functional programming languages and variables are immutable, so it would be much easier to make this possible, but just in case if Python also has similar functionalities, I would like to know.

5.有什么方法可以检查我的类型提示是否正确?

或者至少让它在编译时/运行时向我显示一些警告/错误,以便使我知道出了点问题.

Or at least let it show me some warning / error at compile time / runtime so that I am aware that something is wrong.

在撰写本文时,最新的稳定版本是3.8.0.

At the time of this writing, the latest stable version is 3.8.0.

推荐答案

1. map 的返回类型是什么?

1. What is the return type of map?

map 的返回值

map’s return value is currently typed as an Iterator[T]. Since iterators are iterables, your annotation of x: Iterable[float] = map(int.__float__, [1, 2, 3]) is valid. (Also, just write map(float, [1, 2, 3]).)

2.从广义上讲,地图的功能签名"是什么?

目前无法表示,这就是为什么一个相关问题)

It’s currently impossible to represent, which is why typeshed has overloads for up to 6 generic parameters. (one related issue)

3.通常,在哪里可以找到Python函数/方法的正确类型提示,包括内置函数,核心库中的内置函数?

主要出于学习目的,我需要它们.

I need them mainly for learning purpose.

Python的类型化存储库.请注意,出于学习目的(练习),通常应该推断类型,或者使用有意义的类型而不是最准确的类型.

Python’s typeshed repository. Note that for non-learning purposes – practice – you should generally either let the type be inferred or use whatever type makes sense rather than the most exact type possible.

您还可以使用 reveal_type –参见下文.

You can also use reveal_type – see below.

4.有没有办法像Haskell或Erlang那样输出由编译器/解释器计算出的类型推断结果?

我知道Haskell和Erlang是函数式编程语言,并且变量是不可变的,因此使之成为可能会容易得多,但是如果万一Python也具有类似的功能,我想知道.

I know Haskell and Erlang are functional programming languages and variables are immutable, so it would be much easier to make this possible, but just in case if Python also has similar functionalities, I would like to know.

这取决于类型检查器.Mypy具有 reveal_type .

This is up to your typechecker. Mypy has reveal_type.

x = map(float, [1, 2, 3])
reveal_type(x)  # note: Revealed type is 'typing.Iterator[builtins.float*]'

5.有什么方法可以检查我的类型提示是否正确?

或者至少让它在编译时/运行时向我显示一些警告/错误,以便使我知道出了点问题.

Or at least let it show me some warning / error at compile time / runtime so that I am aware that something is wrong.

通常,这就是类型检查.(例如,Mypy会告诉您 x 提示是否错误.)它无法捕获所有内容,尤其是在像Python这样动态的语言中,但这就是编程的本质.

Statically, that’s what typechecking is. (For example, Mypy would have told you if your x hint were wrong.) It can’t catch everything, especially in a language as dynamic as Python, but that’s the nature of programming.

有一些项目基于类型注释进行某种程度的运行时断言,但是我没有使用过,或者真的会打扰到它.

There are a few projects that do some level of runtime assertions based on type annotations, but none I’ve used or would really bother with.

这篇关于查找适当的Python类型提示,例如内置函数map()的签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆