转载请注明出处️

作者:测试蔡坨坨

原文链接:caituotuo.top/b055fbf2.html


你好,我是测试蔡坨坨。

就在前几天,2022年10月24日,Python3.11正式版发布了!

Python官方在2020年1月1日结束了对Python2的维护,这也意味着Python2已经成为历史,真正进入了Python3时代。自从进入Python3版本以来,官方已经发布了众多修改版本分支,现在最新的正式版本就是前不久刚发布的Python3.11,这一版本历经17个月的开发,现在公开可用,据说对用户更友好。

今天,我们就来一起看看Python3.11都更新了些什么呢。

官方文档:https://docs.python.org/3.11/whatsnew/3.11.html

# author: 测试蔡坨坨
# datetime: 2022/10/29 15:14
# function: Python3.11 输出版本信息 import sys print("Python Version: ", sys.version)
# Python Version: 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]
print("Python Version Info: ", sys.version_info)
# Python Version Info: sys.version_info(major=3, minor=11, micro=0, releaselevel='final', serial=0)

速度更快

首先第一点,也是最重要的,就是它更快了,官方说法是Python 3.11比Python 3.10快10-60%。

Python 3.11 is between 10-60% faster than Python 3.10. On average, we measured a 1.25x speedup on the standard benchmark suite. See Faster CPython for details.

众所周知,Python语法简洁、功能强大,特别容易上手,因此使用人数超级多,在众多最受欢迎编程语言榜单中多次位列第一,但是它有一个明显的劣势就是纯Python编写的程序执行效率低,很多开发者都期待这门语言的性能有所提升。

更加人性化的报错

PEP 657: Fine-grained error locations in tracebacks

官方文档:https://docs.python.org/3.11/whatsnew/3.11.html#whatsnew311-pep657

When printing tracebacks, the interpreter will now point to the exact expression that caused the error, instead of just the line.

更加人性化的报错,与之前显示在某一行的报错不同,这个版本的报错会显示具体原因,画出具体位置。

Python编程语言对初学者非常友好,具有易于理解的语法和强大的数据结构,但是对于刚刚接触Python的同学来说却存在一个难题,即如何解释当Python遇到错误时显示的Traceback,有了这个功能就可以帮助用户快速解释错误消息。

举栗:

# author: 测试蔡坨坨
# datetime: 2022/10/29 15:35
# function: PEP 657: Fine-grained error locations in tracebacks # 定义一个函数
def data():
return {
"name": "测试蔡坨坨",
"studying": [
{
"language": "Python",
"version": "3.11"
}
]
} if __name__ == '__main__':
# 调用函数并指定一个错误的索引
print(data()["studying"][2])

一个IndexError的例子,我们可以看到嵌入在Traceback中的~^符号详细地指向导致错误的代码,这种带注释的Traceback对于过于复杂的代码来说是比较友好的。

异常组

PEP 654: Exception Groups and except

官方文档:https://docs.python.org/3.11/whatsnew/3.11.html#whatsnew311-pep654

Exception Groups 让我们的Exception信息具有层次感,之前的Python每次只能处理一个Exception,异常组的使用丰富了Exception的作用,可以引入多个Exception,同时也丰富了我们代码分析的信息量。

举栗:

# author: 测试蔡坨坨
# datetime: 2022/10/29 15:58
# function: PEP 654: Exception Groups and except * from builtins import ExceptionGroup def test():
raise ExceptionGroup(
"异常嵌套关系",
[
ValueError(456),
ExceptionGroup(
"引入第三方库",
[
ImportError("无该模块"),
ModuleNotFoundError("你需要其他模组")
]
),
TypeError("int")
]
) if __name__ == '__main__':
test()

支持TOML配置解析

PEP 680: tomllib — Support for parsing TOML in the Standard Library

官方文档:https://docs.python.org/3/library/tomllib.html#module-tomllib

增加了TOML(Tom's Obvious Minimal Language 的缩写)文件的读取,toml文件与自动化测试框架或Web开发中的config、yaml文件类似,都是通过修改配置文件来保持框架源码的不变。Python社区已将TOML作为首选格式,虽然TOML已被使用多年,但Python并没有内置的TOML支持,而在Python3.11中tomllib已经是个内置模块,这个新模块建立在 toml 第三方库之上,允许解析 TOML 文件。

举栗:

demo.toml:

# This is a TOML document.

title = "测试蔡坨坨"

[info]
name = "caituotuo"
blog = "www.caituotuo.top"
hobby = ["吃饭", "睡觉", "学Python"] [other]
enable = true
# author: 测试蔡坨坨
# datetime: 2022/10/29 16:15
# function: PEP 680: tomllib — Support for parsing TOML in the Standard Library import tomllib def read_toml():
with open("demo.toml", "rb") as f:
data = tomllib.load(f)
print(data) if __name__ == '__main__':
read_toml()
# {'title': '测试蔡坨坨', 'info': {'name': 'caituotuo', 'blog': 'www.caituotuo.top', 'hobby': ['吃饭', '睡觉', '学Python']}, 'other': {'enable': True}}

更加安全

PEP 675: Arbitrary literal string type

官方文档:https://docs.python.org/3/library/typing.html#typing.LiteralString

The new LiteralString annotation may be used to indicate that a function parameter can be of any literal string type. This allows a function to accept arbitrary literal string types, as well as strings created from other literal strings. Type checkers can then enforce that sensitive functions, such as those that execute SQL statements or shell commands, are called only with static arguments, providing protection against injection attacks.

防止SQL注入,指定参数为LiteralString,当传入普通的String时就不可以工作。

# author: 测试蔡坨坨
# datetime: 2022/10/29 16:34
# function: PEP 675: Arbitrary literal string type from typing import LiteralString def run_query(sql: LiteralString):
pass def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
run_query("SELECT * FROM students") # ok
run_query(literal_string) # ok
run_query("SELECT * FROM " + literal_string) # ok
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)

异常Notes

PEP 678: Exceptions can be enriched with notes

官方文档:https://docs.python.org/3/whatsnew/3.11.html#whatsnew311-pep678

常规异常具有添加任意 notes 的扩展能力,可以使用.add_note()向任何异常添加一个note,并通过检查.__notes__属性来查看现有notes。

# author: 测试蔡坨坨
# datetime: 2022/10/29 16:53
# function: PEP 678: Exceptions can be enriched with notes try:
raise TypeError('str')
except TypeError as e:
e.add_note('类型错了')
e.add_note('该用int')
raise e

以上几点就是我认为 Python 3.11 比较有意思的部分,更多内容可参考官方文档,想体验新功能的小伙伴感觉去试试新版本吧 ~

Python3.11正式版,它来了!的更多相关文章

  1. Windows 11正式版来了,下载、安装教程、一起奉上!

    Windows 11正式版已经发布了,今天给大家更新一波Win11系统的安装方法,其实和Win10基本一样,有多种方法.   安装Win11前请先查看电脑是否支持Win11系统,先用微软自家的PC H ...

  2. 升级了 Windows 11 正式版,有坑吗?

    今天磊哥去公司上班,惊喜的发现 Windows 提示更新了,并且是 Windows 11 正式版,这太让人开心了,二话不说"先升为敬". ​ 下载更新 下载完咱就重启更新呗. Wi ...

  3. Windows 11 正式版 Build 22000.194 官方简体中文版、英文版(消费者版、商业版)下载

    昨天阿三正式发布了 Windows 11,版本号竟然是 22000.194,也就是 9 月 16 日的 测试版 22000.194,仅仅是文件改了个名,特别是消费者版本 hash 校验都是一致的. W ...

  4. Linux Kernel 3.11 正式版发布

    Linus 发布 了 3.11 版本的 Linux 内核.该版本值得关注的新特性有: Lustre 分布式文件系统.透明的 ARM 架构的大数据页支持:ARM64 上的 Xen 和 KVM 虚拟化:O ...

  5. macOS Big Sur 11.4 (20F71) 正式版(DMG、ISO、IPSW),百度网盘下载

    本站提供的 macOS Big Sur 软件包,既可以拖拽到 Applications(应用程序)下直接安装,也可以制作启动 U 盘安装,或者在虚拟机中启动安装. 请访问原文链接:https://sy ...

  6. macOS Big Sur 11.3 (20E232) 正式版发布,百度网盘下载

    本站提供的 macOS Big Sur 软件包,即可以直接拖拽到 Applications(应用程序)下直接安装,也可以制作启动 U 盘安装,或者直接在虚拟机中启动安装. 请访问原文链接:https: ...

  7. 制作正式版10.11 OS X El Capitan 安装U盘(优盘)

    一.准备工作:1.准备一个 8GB 或以上容量的 U 盘,确保里面的数据已经妥善备份好(该过程会抹掉 U 盘全部数据)2.从官网Appstore下载下来的 “安装 OS X El Capitan”,当 ...

  8. iOS 11.4.1 正式版越狱

    在 2018 年 Electra 最新能支持到 11.3.1 越狱,很长的一段时间 11.4 只能支持 Beta 版本,临近春节给了我们一个大礼物,终于支持 iOS 11.4-11.4.1,目前 iO ...

  9. MySQL 8.0 正式版 8.0.11 发布:比 MySQL 5.7 快 2 倍

    ySQL 8.0 正式版 8.0.11 已发布,官方表示 MySQL 8 要比 MySQL 5.7 快 2 倍,还带来了大量的改进和更快的性能! 注意:从 MySQL 5.7 升级到 MySQL 8. ...

随机推荐

  1. .NET异步编程模式(一)

    .NET 提供了三种异步编程模型 TAP - task-based asynchronous pattern APM - asynchronous programming model EAP - ev ...

  2. SpringBoot项目搭建 + Jwt登录

    临时接了一个小项目,有需要搭一个小项目,简单记录一下项目搭建过程以及整合登录功能. 1.首先拿到的是一个码云地址,里面是一个空的文件夹,只有一个 2. 拿到HTTPS码云项目地址链接,在IDEA中cl ...

  3. 硬件错误导致的crash

    [683650.031028] BUG: unable to handle kernel paging request at 000000000001b790--------------------- ...

  4. tqdm和zip组合使用时无法显示进度条-解决办法

    问题 单独对于可迭代对象iterator使用tqdm时,结合循环就可以在终端显示进度条, 以直观展示程序进度,如下: from tqdm import tqdm textlist = [] for i ...

  5. 手把手教你搭建规范的团队vue项目,包含commitlint,eslint,prettier,husky,commitizen等等

    目录 1,前言 2,创建项目 2,安装vue全家桶 3,配置prettier 4,配置eslint 5,配置husky + git钩子 6,配置commitlint 6.1,配置commitlint格 ...

  6. 如何在 Windows 和 Linux 上确定系统使用的是 MBR 分区还是 GPT 分区详细步骤!!!

    在 Windows 上检查系统使用的是 MBR 分区还是 GPT 分区 点击放大镜搜索输入disk 点击打开 进入之后,右键点击你想要检查分区方案的磁盘,在右键菜单里选择属性! 在属性窗口,切换到卷, ...

  7. day31-线程基础01

    线程基础01 1.程序 进程 线程 程序(program):是为完成的特定任务,用某种语言编写的一组指令的集合.简单来说,就是我们写的代码. 进程: 进程是指运行中的程序,比如我们使用QQ,就启动了一 ...

  8. aardio 编程语言快速入门 —— 语法速览

    本文仅供有编程基础的用户快速了解常用语法.如果『没有编程基础』 ,那么您可以通过学习任何一门编程语言去弥补你的编程基础,不同编程语言虽然语法不同 -- 编程基础与经验都是可以互通的.我经常看到一些新手 ...

  9. MySQL InnoDB缓存

    1. 背景 对于各种用户数据.索引数据等各种数据都是需要持久化存储到磁盘,然后以"页"为单位进行读写. 相对于直接读写缓存,磁盘IO的成本相当高昂. 对于读取的页面数据,并不是使用 ...

  10. SpringBoot Xml转Json对象

    一.导入需要的依赖 <dependency> <groupId>maven</groupId> <artifactId>dom4j</artifa ...