在 Python 中注释函数
时间:2024-12-31 16:46:07 200浏览 收藏
本篇文章向大家介绍《在 Python 中注释函数》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

最近,我撰写了一篇关于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{ stores: type[] = [] constructor(){ this.stores = [] } add(item: type){ this.stores.push(item) } } const g1 = new genericstore (); //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
为什么要学习Python函数注释?
函数注释有助于构建更强大的类型系统,从而减少错误的可能性(尤其是在使用mypy等静态类型检查器时)。此外,当使用强大的类型系统编写库(或SDK)时,可以显著提高使用该库的开发人员的工作效率(主要是因为编辑器的代码提示)。
如果您有任何疑问或发现本文中的错误,请随时在评论区留言。
本篇关于《在 Python 中注释函数》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
文章 · python教程 | 2天前 | 日志 · 工程化 · 异步编程 · 故障排查 · 可观测性 · Python教程 · Python 异步任务 可观测性 logging contextvars 生产实践 QueueHandler QueueListener request_id JSON日志189 收藏
-
文章 · python教程 | 3天前 | 依赖管理 · 工程化 · CI · 生产实践 · Python教程 · 打包发布 · Python build 依赖管理 twine wheel 打包发布 pyproject.toml dependency-groups pylock.toml sdist479 收藏
-
文章 · python教程 | 3天前 | WEB开发 · 工程化 · 配置管理 · flask · 生产实践 · Python教程 · Python Flask G 配置管理 请求上下文 应用上下文 生产实践 current_app teardown app factory257 收藏
-
文章 · python教程 | 3天前 | ORM · Django · 异步编程 · 生产实践 · Python教程 · 后端开发 · Python Django 性能优化 orm 事务 ASGI 生产实践 async view sync_to_async310 收藏
-
文章 · python教程 | 3天前 | 性能优化 · 异步编程 · fastapi · 生产实践 · Python教程 · API服务 · Python API服务 FastAPI asyncio httpx 生产实践 lifespan BackgroundTasks run_in_threadpool411 收藏
-
文章 · python教程 | 4天前 | 工程化 · 自动化测试 · pytest · CI · 生产实践 · Python教程 · Python CI pytest fixture tmp_path monkeypatch pytest-xdist 测试稳定性303 收藏
-
文章 · python教程 | 4天前 | sqlalchemy · 异步编程 · fastapi · 生产实践 · Python教程 · Python 连接池 FastAPI sqlalchemy asyncio AsyncSession340 收藏
-
文章 · python教程 | 4天前 | 性能优化 · fastapi · 生产实践 · Python教程 · Pydantic · Python 性能优化 FastAPI Pydantic v2 TypeAdapter validate_json342 收藏
-
文章 · python教程 | 4天前 | 性能优化 · gil · 生产实践 · Python教程 · CPython · Python 性能优化 线程安全 gil CPython free-threaded381 收藏
-
文章 · python教程 | 5天前 | 异步编程 · fastapi · 后端架构 · Python教程 · asyncio · Python 异步编程 FastAPI asyncio TaskGroup 生产实践496 收藏
-
447 收藏
-
189 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习