python3.10 新的特性介绍

2024-05-12 01:32
文章标签 特性 介绍 python3.10

本文主要是介绍python3.10 新的特性介绍,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

python3.10 新的特性介绍

文章目录

    • python3.10 新的特性介绍
      • with 嵌套语句的使用 新增
      • Match case 语句 新增
        • 匹配对象
        • 匹配状态码
        • 匹配枚举类型的变量
      • 或操作符新的含义
      • 其他
    • 参考文档

Python3.10 发布也有一段时间了,新的版本提供了一些好用的功能,可能比较关注的就是 match case 这个多分支选择语法。 以及 with 语句 的改进等。

with 嵌套语句的使用 新增

with 语句 可以同时 进行 多个 with ,打开多个上下文管理器。

import os
import os.path
from typing import List# 源路径
src_path = r'C:\Users\XXX\XXXX\XXX\XXXXX'# 目标路径
dst_path = r'C:\Users\AAA\BBBB\CCCC'def get_filelist(path: str) -> List:"""返回 当前路径下面所有的文件名称:param path::return:"""results = []for home, dirs, files in os.walk(path):for filename in files:ab_path = os.path.join(home, filename)results.append(ab_path)return resultsdef add_head_footer(xml_string: str):"""add lncr head  and footer"""head = 'this is head'footer = 'this is footer'return head + xml_string + footer# python.3.10 以前的写法
def add_header_xml():src_files = get_filelist(src_path)for full_file in src_files:file_name = os.path.basename(full_file)with open(os.path.join(dst_path, file_name), 'w', encoding='utf-8') as f:with open(os.path.join(src_path, file_name), 'r', encoding='utf-8') as fout:src_xml = fout.read()head_string = add_head_footer(src_xml)try:f.write(head_string)except (UnicodeError, UnicodeEncodeError) as e:print(f"file_name :{file_name},e:{e}")print(f"{file_name} deal done.")

如果使用with 嵌套语句, 在with 可以打开多个文件, 一个作为源, 一个作为写入的文件。

下面是在python3.10 解释器下面

# python.3.10 的写法
def add_header_xml():src_files = get_filelist(src_path)for full_file in src_files:file_name = os.path.basename(full_file)with (open(os.path.join(dst_path, file_name), 'w', encoding='utf-8') as f,open(os.path.join(src_path, file_name), 'r', encoding='utf-8') as fout,                                                                                 ):src_xml = fout.read()head_string = add_head_footer(src_xml)try:f.write(head_string)except (UnicodeError,UnicodeEncodeError) as e:print(f"file_name :{file_name},e:{e}")print(f"{file_name} deal done." )

是不是看起来比以前 舒服一些了呢。

Match case 语句 新增

PEP 634: Structural Pattern Matching

千呼万唤始出来, 终于python 也出现了 其他语言中 switch 语句的功能, python 使用的是 match case 语法来完成多分支选择 。

匹配对象
from dataclasses import dataclassfrom enum import Enum@dataclass
class Point:x: inty: intdef location(point:Point):match point:case Point(x=0, y=0):print("Origin is the point's location.")case Point(x=0, y=y):print(f"Y={y} and the point is on the y-axis.")case Point(x=x, y=0):print(f"X={x} and the point is on the x-axis.")case Point():print("The point is located somewhere else on the plane.")case _:print("Not a point")if __name__ == '__main__':p = Point(x=1,y=0)location(p)

甚至可以嵌套


from dataclasses import dataclass
from enum import Enum
from typing import List @dataclass
class Point:x: inty: intdef location(points:List[Point] ):match points:case []:print("No points in the list.")case [Point(0, 0)]:print("The origin is the only point in the list.")case [Point(x, y)]:print(f"A single point {x}, {y} is in the list.")case [Point(0, y1), Point(0, y2)]:print(f"Two points on the Y axis at {y1}, {y2} are in the list.")case _:print("Something else is found in the list.")if __name__ == '__main__':passp = Point(x=0,y=1)p2 = Point(x=0,y=2)location([p,p2])  # Two points on the Y axis at 1, 2 are in the list.p = Point(x=1,y=3)location([p]) # A single point 1, 3 is in the list.location([]) # No points in the list.

case 中也可以添加 一些判断条件。 比如 x==y, x>y

match point:case Point(x, y) if x == y:print(f"The point is located on the diagonal Y=X at {x}.")case Point(x, y):print(f"Point is not on the diagonal.")
匹配状态码
            def http_error(status):match status:case 400:return "Bad request"case 404:return "Not found"case 418:return "I'm a teapot"case _:return "Something's wrong with the internet"if __name__ == '__main__':print(http_error('400'))print(http_error(400))

如果要匹配多个状态码 ,可以使用 | 或 运算符来完成。

case 401 | 403 | 404:return "Not allowed"
匹配枚举类型的变量

如果匹配 条件中有一部分重合的条件,从上到下匹配, 先匹配成功之后,进入对应的case ,其他的case 语句 将不会进入了。 case _ 如果没有前面都没有匹配到, 这个是兜底策略,一定会进入这个 case 语句。

class Color(Enum):RED = 0GREEN = 1BLUE = 2BLACK = 3 def which_color(color):match color:case Color.RED:print("I see red!")case Color.BLUE|Color.GREEN:print("I'm feeling the blues.")case Color.GREEN:print("Grass is green")case _ :print("Sorry, I'm not find color.")if __name__ == '__main__':passcolor = Color.GREENwhich_color(color) # I'm feeling the bluescolor = Color.BLACKwhich_color(color) # Sorry, I'm not find color.

或操作符新的含义

在Python 3.10中, | 符号有的新语法,可以表示x类型 或 Y类型,以取代之前的typing.Union 完成类型注解.

在3.10 以前写 参数注解,如果参数中有可能有两种类型, 就需要使用 Union 来指定类型。

例如:

from typing import Uniondef double(value: Union[int, str]) -> Union[int, str]:return value*2

现在可以使用 | 来指定类型

def double(value: str | int) -> str | int:return value * 2if __name__ == '__main__':		print(double('name'))print(double(10))

这个新的定义也可以使用在 isinstance() and issubclass() 函数中。

>>> isinstance(5,int|str|dict)
True

其他

报错更加明确以及 精确到行的报错,指出对应的行数,以及对一些模块的性能提升。

参考文档

what’s new 3.10

pep0634

Python 3.10 中新的功能和变化

分享快乐,留住感动. '2022-02-08 21:24:26' --frank

这篇关于python3.10 新的特性介绍的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/981226

相关文章

Spring Boot3.0新特性全面解析与应用实战

《SpringBoot3.0新特性全面解析与应用实战》SpringBoot3.0作为Spring生态系统的一个重要里程碑,带来了众多令人兴奋的新特性和改进,本文将深入解析SpringBoot3.0的... 目录核心变化概览Java版本要求提升迁移至Jakarta EE重要新特性详解1. Native Ima

zookeeper端口说明及介绍

《zookeeper端口说明及介绍》:本文主要介绍zookeeper端口说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、zookeeper有三个端口(可以修改)aVNMqvZ二、3个端口的作用三、部署时注意总China编程结一、zookeeper有三个端口(可以

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

HTML img标签和超链接标签详细介绍

《HTMLimg标签和超链接标签详细介绍》:本文主要介绍了HTML中img标签的使用,包括src属性(指定图片路径)、相对/绝对路径区别、alt替代文本、title提示、宽高控制及边框设置等,详细内容请阅读本文,希望能对你有所帮助... 目录img 标签src 属性alt 属性title 属性width/h

MybatisPlus service接口功能介绍

《MybatisPlusservice接口功能介绍》:本文主要介绍MybatisPlusservice接口功能介绍,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友... 目录Service接口基本用法进阶用法总结:Lambda方法Service接口基本用法MyBATisP

MySQL复杂SQL之多表联查/子查询详细介绍(最新整理)

《MySQL复杂SQL之多表联查/子查询详细介绍(最新整理)》掌握多表联查(INNERJOIN,LEFTJOIN,RIGHTJOIN,FULLJOIN)和子查询(标量、列、行、表子查询、相关/非相关、... 目录第一部分:多表联查 (JOIN Operations)1. 连接的类型 (JOIN Types)

java中BigDecimal里面的subtract函数介绍及实现方法

《java中BigDecimal里面的subtract函数介绍及实现方法》在Java中实现减法操作需要根据数据类型选择不同方法,主要分为数值型减法和字符串减法两种场景,本文给大家介绍java中BigD... 目录Java中BigDecimal里面的subtract函数的意思?一、数值型减法(高精度计算)1.

Pytorch介绍与安装过程

《Pytorch介绍与安装过程》PyTorch因其直观的设计、卓越的灵活性以及强大的动态计算图功能,迅速在学术界和工业界获得了广泛认可,成为当前深度学习研究和开发的主流工具之一,本文给大家介绍Pyto... 目录1、Pytorch介绍1.1、核心理念1.2、核心组件与功能1.3、适用场景与优势总结1.4、优