python 3.10 的新特性用不到,你来打我!!!

简介: python 3.10 已经在 10月 4 号发布了,这次更新了错误语法提示对 python 新手更加友好。好几个新的特性非常的有用,一起来看看吧。

更细致的错误语法提示

在调试代码的时候可以精确定位到错误语法的那行,而不是提示 SyntaxError 的行。

# 1
expected = {9: 1, 18: 2, 19: 2, 27: 3, 
some_other_code = foo()
# 2
foo(x, z for z in range(10), t, w)
# 3 
try:
    build_dyson_sphere()
except NotEnoughScienceError, NotEnoughResourcesError:
# 4
f"Black holes {*all_black_holes} and revelations"
# 5
schwarzschild_black_hole = None
schwarschild_black_hole

3.9 提示的是

# 1 
    some_other_code = foo()
                    ^
SyntaxError: invalid syntax
# 2 
    foo(x, z for z in range(10), t, w)
           ^
SyntaxError: Generator expression must be parenthesized
# 3
    except NotEnoughScienceError, NotEnoughResourcesError:
                                ^
SyntaxError: invalid syntax
# 4
    (*all_black_holes)
     ^
SyntaxError: f-string: can't use starred expression here
# 5
    schwarschild_black_hole
NameError: name 'schwarschild_black_hole' is not defined

3.10 提示的是

# 1
    expected = {9: 1, 18: 2, 19: 2, 27: 3, 
               ^
SyntaxError: '{' was never closed
# 2
    foo(x, z for z in range(10), t, w)
           ^^^^^^^^^^^^^^^^^^^^
SyntaxError: Generator expression must be parenthesized
# 3
    except NotEnoughScienceError, NotEnoughResourcesError:
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: multiple exception types must be parenthesized
# 4
    (*all_black_holes)
     ^^^^^^^^^^^^^^^^
SyntaxError: f-string: cannot use starred expression here
# 5
    schwarschild_black_hole
NameError: name 'schwarschild_black_hole' is not defined. Did you mean: 'schwarzschild_black_hole'?

结构化模式匹配:match...case

相当于其他语言的 switch...case

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

关键字 match 后跟变量名。 如果匹配,则将执行 case 块内的语句, 没有匹配,则执行 case _ 块内的语句。

# 1
for i in [1,2,3,4,5,6,7]:
    match i:
        case 1:
            print('周一')
        case 2:
            print('周二')
        case 3:
            print('周三')
        case 4:
            print('周四')
        case 5:
            print('周五')
        case _:
            print('放假了')

结果:

# 1
周一
周二
周三
周四
周五
放假了
放假了

再来一个 tuple 类型的

# 2
point = (1, 2, 3)
match point:
    case (0, 0, _):
        print("原点")
    case (0, y, 0):
        print(f"Y={y}")
    case (x, 0, 0):
        print(f"X={x}")
    case (x, y, z):
        print(f"X={x}, Y={y}, Z={z}")
    case _:
        raise ValueError("Not a point")

结果:

# 2
X=1, Y=2, Z=3

可以使用 tuple 类型,当然也可以使用 list 类型,类似于:points = [(1, 3),(1, 2)]

新型联合运算符

以 X|Y 的形式引入了新的类型联合运算符。

def square(number: int|float): 
    return number ** 2
print(square(4))
print(square(4.4))

结果:

16
19.360000000000003

也可以用作 isinstance():一个对象是否是一个已知的类型 和 issubclass():判断参数 class 是否是类型参数 classinfo 的子类 的第二个参数。

isinstance("5",int|str) 
isinstance("xxxx",int|str)

结果:

True
True

zip 的严格模式

函数 zip() 增加 strict 参数,如果设置 strict = True,而传输的参数的长度不相等将会抛出异常。

x = [1,2,3,4,5]
y = [1,2,3]
z = zip(x,y, strict=True)
print(list(z))

结果:

ValueError: zip() argument 2 is shorter than argument 1

字典增加了 mapping 属性

dict.items()、dict.keys()、dict.values() 分别增加了 mapping 属性

x = {'name': '张三', 'age': 14}
keys = x.keys()
values = x.values()
items = x.items()
print(keys.mapping)
print(values.mapping)
print(items.mapping)

总结

python 3.10 更新的最有用的就是错误提示了,再也不会看到提示一团迷糊,定位更加的精确,match...case 终于来了。

目录
相关文章
|
关系型数据库 数据库 PostgreSQL
【一文搞懂PGSQL】1.简述和安装
PostgreSQL(简称PG或PGSQL)是一款使用C和C++语言开发的开源关系型数据库管理系统。其官网为 [www.postgresql.org](https://www.postgresql.org/),中文社区为 [www.postgres.cn](http://www.postgres.cn)。PG采用了多层逻辑结构:第一层为实例,第二层为数据库(每个实例下可有多个相互独立的数据库),第三层为Schema(每个数据库下包含多个Schema)。每个Schema下可以创建表、视图、索引、函数等数据库对象。
|
缓存 固态存储 Java
Elasticsearch 的扩展性和性能调优
【9月更文第2天】Elasticsearch 是一个分布式的搜索和分析引擎,适用于各种大规模数据处理场景。随着数据量的增长和查询复杂度的增加,Elasticsearch 的性能优化变得尤为重要。本文将详细介绍如何通过硬件配置、集群规模调整以及查询优化策略来提升 Elasticsearch 的性能。
576 6
|
存储 Apache 文件存储
在Apache环境下为Web网站增设访问控制:实战指南
在Apache服务器上保护网站资源涉及启用访问控制模块(`mod_authz_core`和`mod_auth_basic`),在`.htaccess`或`httpd.conf`中设定权限,如限制对特定目录的访问。创建`.htpasswd`文件存储用户名和密码,并使用`htpasswd`工具管理用户。完成配置后重启Apache服务,访问受限目录时需提供有效的用户名和密码。对于高安全性需求,可考虑更复杂的认证方法。【6月更文挑战第20天】
752 4
|
关系型数据库 MySQL 数据库
轻松入门:使用Docker安装MySQL数据库的完全指南
轻松入门:使用Docker安装MySQL数据库的完全指南
|
存储 安全 Java
走进 JDK 之 PriorityQueue
这是 Java 集合框架的第三篇文章了,前两篇分别解析了 ArrayList 和 LinkedList,它们分别是基于动态数组和链表来实现的。今天来说说 Java 中的优先级队列 PriorityQueue,它是基于堆实现的,后面也会介绍堆的相关概念。
走进 JDK 之 PriorityQueue
|
存储 DataWorks 算法
dataworks数据集成小记-文本数据
dataworks离线数据集成使用datax来实现同步,文本数据包括TxtFileReader\OSS\ftp 三类数据源
347 0
|
监控 容器
Filebeat配置顶级字段Logstash在output输出到Elasticsearch中的使用
Filebeat配置顶级字段Logstash在output输出到Elasticsearch中的使用
330 0
浅谈RISC-V指令集的基本指令格式和立即数操作
在以前的文章中,我分享了RISC-V在设计的初衷,除了可以被通用软件开发使用之外,还有一个目的就是,可以支持更多定制化的设计。也就是说,用户可以在基本指令集上面,进行一个或者多个的指令集扩展操作,但是有一个条件,不能再重新定义基本指令集。也就是说,任何一款基于RISC-V指令集的处理器,都要能够支撑整数基本指令集。可以看出基本指令集的重要性。
1655 0
|
算法 定位技术
基于Astar算法的栅格地图目标最短路径搜索算法MATLAB仿真,带GUI界面
基于Astar算法的栅格地图目标最短路径搜索算法MATLAB仿真,带GUI界面
328 0
基于Astar算法的栅格地图目标最短路径搜索算法MATLAB仿真,带GUI界面