最近,我撰写了一篇关于TypeScript函数注释的博文。 深入研究后,我了解了更多关于Python函数注释的知识。 本文将使用与上一篇博文类似的示例,讲解Python函数的注释方法。
您可以通过将python.analysis.typecheckingMode
设置为basic
、standard
或strict
来验证Visual Studio Code中的类型注释。 basic
和standard
选项不一定能保证您对函数和变量的注释正确性,但strict
模式可以。
您可以在Python中返回函数,并将函数作为值传递。回调函数实际上使用callable
类型进行注释,其语法如下:
callable[[argtype1, argtype2, argtype3], returntype]
例如,函数length(text: str) -> int
将被注释为callable[[str], int]
。
例如,JavaScript中的这个函数:
function multiplier(factor){
return value => factor * value
}
const n = multiplier(6)
n(8) // 48
在Python中可以这样写:
def multiplier(factor):
def inner(value):
return value * factor
return inner
n = multiplier(6)
n(8) # 48
我们可以创建一个名为number
的类型别名,它是int
和float
的联合类型:
from typing import typealias, Union
number: typealias = Union[int, float]
将参数视为JavaScript数字。
因此,要注释此函数,我们有:
def multiplier(factor: number) -> callable[[number], number]:
def inner(value: number) -> number:
return value * factor
return inner
a = multiplier(4.5)
a(3) # 13.5
经典的泛型函数示例是:
def pick(array, index):
return array[index]
pick([1,2,3], 2) # 3
使用TypeVar
,我们可以创建更详细的泛型信息(比TypeScript更详细)。
from typing import TypeVar
t = TypeVar("t") # 参数名和变量名必须相同
这样我们就有:
from typing import TypeVar, Sequence
def pick(array: Sequence[t], index: int) -> t:
return array[index]
print(pick([1,2,3,4], 2))
那么自定义mymap
函数呢?它的作用类似于JavaScript中的map
函数。
注意: Python中的
map()
返回的是迭代器,而不是列表。
def mymap(array, fn):
return map(fn, array)
def twice(n): return n * 2
print(mymap([1,2,3], twice))
我们可以混合使用callable
和TypeVar
类型来注释此函数。
from typing import TypeVar, Iterable, Callable
input_type = TypeVar("input_type")
output_type = TypeVar("output_type")
def mymap(array: Iterable[input_type], fn: Callable[[input_type], output_type]) -> Iterable[output_type]:
return map(fn, array)
def twice(n: int) -> int: return n * 2
print(mymap([1,2,3], twice))
或者我们可以为callable
函数创建别名:
from typing import TypeVar, Iterable, Callable
input_type = TypeVar("input_type")
output_type = TypeVar("output_type")
MappableFunction = Callable[[input_type], output_type]
def mymap(array: Iterable[input_type], fn: MappableFunction) -> Iterable[output_type]:
return map(fn, array)
MappableFunction
接受泛型类型输入和输出,并将它们应用到Callable[[input_type], output_type]
上下文中。
思考一下myfilter
函数该如何注释?
如果您想到了这个:
from typing import Iterable, TypeVar, Callable
input_type = TypeVar("input_type")
def myfilter(array: Iterable[input_type], fn: Callable[[input_type], bool]) -> Iterable[input_type]:
return filter(fn, array)
您答对了!
Python中的泛型类与TypeScript中的定义方式有所不同。
在TypeScript中,您可以这样定义:
class genericstore<type>{
stores: type[] = []
constructor(){
this.stores = []
}
add(item: type){
this.stores.push(item)
}
}
const g1 = new genericstore<string>(); //g1.stores: string[]
g1.add("hello") // only strings are allowed
但在Python中,它们相当不同。
Generic
类型,然后让它们成为泛型类的子类。因此,要在Python中重新创建这个GenericStore
类:
from typing import Generic, TypeVar
from dataclasses import dataclass
Type = TypeVar("Type")
@dataclass
class GenericStore(Generic[Type]):
store: list[Type] = []
def add(self, item: Type) -> None:
self.store.append(item)
g1 = GenericStore([True, False]) # g1.store: list[bool]
g1.add(False) # only bool is allowed
函数注释有助于构建更强大的类型系统,从而减少错误的可能性(尤其是在使用mypy
等静态类型检查器时)。此外,当使用强大的类型系统编写库(或SDK)时,可以显著提高使用该库的开发人员的工作效率(主要是因为编辑器的代码提示)。
如果您有任何疑问或发现本文中的错误,请随时在评论区留言。