- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
在 Python 3.5 或更高版本中,支持类型提示(有关更多信息,请参阅 here)。但是,常见类型的正确用法并没有很好的记录。
例如,从官方网站,我可以收集到以下(正确的)用法:
字符串
# 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
float
# 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
的返回类型是什么?
from typing import Iterable
# Is this correct?
x: Iterable[float] = map(int.__float__, [1, 2, 3])
我不确定这是否是上面 x
的正确类型提示。
<强>2。从广义上讲,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函数是可以接受多个iterables的。是documented作为:
map(function, iterable, ...)
可以这样使用:
# 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]]
一般来说,我猜应该是这样的,但是这不是正确的写法:
FunctionN = Callable[[T1, T2, ..., Tn], R]
typeOfMap = Callable[[FunctionN, Iterable[T1], Iterable[T2], ..., Iterable[Tn]], Iterable[R]]
那么,正确的写法是什么?
<强>3。一般来说,我在哪里可以找到 Python 函数/方法的正确类型提示,包括内置的、核心库中的类型提示?
我需要它们主要是为了学习目的。
<强>4。有什么方法可以像 Haskell 或 Erlang 那样输出编译器/解释器计算出的类型推断结果吗?
我知道 Haskell 和 Erlang 是函数式编程语言,变量是不可变的,因此实现这一点会容易得多,但以防万一 Python 也具有类似的功能,我想知道。
<强>5。有什么方法可以检查我的类型提示是否正确?
或者至少让它在编译时/运行时向我显示一些警告/错误,这样我就知道出了什么问题。
在撰写本文时,最新的稳定版本是 3.8.0。
最佳答案
1. What is the return type of
map
?
map
的返回值 is currently typed as an Iterator[T]
.由于迭代器是可迭代的,因此您对 x: Iterable[float] = map(int.__float__, [1, 2, 3])
的注释是有效的。 (此外,只需编写 map(float, [1, 2, 3])
。)
2. In a broader sense, what is the 'function signature' of map?
目前无法表示,这就是为什么typeshed has overloads for up to 6 generic parameters . ( one related issue )
3. In general, where can I find the correct type hint of a Python function / method, including the built-in ones, those in the core libraries?
I need them mainly for learning purpose.
Python 的 typeshed repository .请注意,对于非学习目的——练习——你通常应该让类型被推断或使用任何有意义的类型而不是尽可能最精确的类型。
您还可以使用 reveal_type
– 见下文。
4. Is there any way to output the type inference result computed by the compiler / interpreter, as in Haskell or Erlang?
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
.
x = map(float, [1, 2, 3])
reveal_type(x) # note: Revealed type is 'typing.Iterator[builtins.float*]'
5. Is there any way to check that my type hint is correct?
Or at least let it show me some warning / error at compile time / runtime so that I am aware that something is wrong.
从静态上讲,这就是类型检查。 (例如,如果您的 x
提示错误,Mypy 会告诉您。)它无法捕获所有内容,尤其是在像 Python 这样动态的语言中,但这就是编程的本质。
有一些项目基于类型注释执行某种级别的运行时断言,但我没有使用过也不会真正打扰。
关于python - 找到合适的 Python 类型提示,例如,内置函数 map() 的签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58465482/
我正在尝试编写一个相当多态的库。我遇到了一种更容易表现出来却很难说出来的情况。它看起来有点像这样: {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE
谁能解释一下这个表达式是如何工作的? type = type || 'any'; 这是否意味着如果类型未定义则使用“任意”? 最佳答案 如果 type 为“falsy”(即 false,或 undef
我有一个界面,在IAnimal.fs中, namespace Kingdom type IAnimal = abstract member Eat : Food -> unit 以及另一个成功
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: What is the difference between (type)value and type(va
在 C# 中,default(Nullable) 之间有区别吗? (或 default(long?) )和 default(long) ? Long只是一个例子,它可以是任何其他struct类型。 最
假设我有一个案例类: case class Foo(num: Int, str: String, bool: Boolean) 现在我还有一个简单的包装器: sealed trait Wrapper[
这个问题在这里已经有了答案: Create C# delegate type with ref parameter at runtime (1 个回答) 关闭 2 年前。 为了即时创建委托(dele
我正在尝试获取图像的 dct。一开始我遇到了错误 The function/feature is not implemented (Odd-size DCT's are not implemented
我正在尝试使用 AFNetworking 的 AFPropertyListRequestOperation,但是当我尝试下载它时,出现错误 预期的内容类型{( “应用程序/x-plist” )}, 得
我在下面收到错误。我知道这段代码的意思,但我不知道界面应该是什么样子: Element implicitly has an 'any' type because index expression is
我尝试将 SignalType 从 ReactiveCocoa 扩展为自定义 ErrorType,代码如下所示 enum MyError: ErrorType { // .. cases }
我无法在任何其他问题中找到答案。假设我有一个抽象父类(super class) Abstract0,它有两个子类 Concrete1 和 Concrete1。我希望能够在 Abstract0 中定义类
我想知道为什么这个索引没有用在 RANGE 类型中,而是用在 INDEX 中: 索引: CREATE INDEX myindex ON orders(order_date); 查询: EXPLAIN
我正在使用 RxJava,现在我尝试通过提供 lambda 来订阅可观察对象: observableProvider.stringForKey(CURRENT_DELETED_ID) .sub
我已经尝试了几乎所有解决问题的方法,其中包括。为 提供类型使用app.use(express.static('public'))还有更多,但我似乎无法为此找到解决方案。 index.js : imp
以下哪个 CSS 选择器更快? input[type="submit"] { /* styles */ } 或 [type="submit"] { /* styles */ } 只是好
我不知道这个设置有什么问题,我在 IDEA 中获得了所有注释(@Controller、@Repository、@Service),它在行号左侧显示 bean,然后转到该 bean。 这是错误: 14-
我听从了建议 registering java function as a callback in C function并且可以使用“简单”类型(例如整数和字符串)进行回调,例如: jstring j
有一些 java 类,加载到 Oracle 数据库(版本 11g)和 pl/sql 函数包装器: create or replace function getDataFromJava( in_uLis
我已经从 David Walsh 的 css 动画回调中获取代码并将其修改为 TypeScript。但是,我收到一个错误,我不知道为什么: interface IBrowserPrefix { [
我是一名优秀的程序员,十分优秀!