Python3.10版本的新特性介绍

3.10正式版发布

Python近几年来越来越火了,而且版本也一直在不停的更新迭代中。Python在2021/10/04发布了3.10的正式版,虽然你可能还没有升级,不过也可以先大概了解一下在新的版本中做了哪些改动哟。

官方的升级介绍(相比3.9版本):

https://docs.python.org/3/whatsnew/3.10.html

1、错误提示变得更加友好

以前写脚本的时候,如果写了一行脚本,少写了一个括号啥的,错误提示不够直观,找错误还得找半天。

下面看下python3.9版本中的错误提示:

    a = (1,2,3


    Python3.10版本的新特性介绍


    同样的脚本,再看下python3.10版本下的提示:


    Python3.10版本的新特性介绍


    what?是的,你没有看错,python会告诉你括号没有成对出现。

    那是不是所有的错误,都能够提醒的这么智能呢?当时不是,有可能是现在新版本才刚出来,对比比较复杂的写法支持的还不够好,下面这个例子提示的就不够直观:


    Python3.10版本的新特性介绍


    同样是少了一个括号,看来能识别的场景有限呀,期待后面能变得更加强大。

    2、加入了match case的用法

    match ... case 语法类似于其它语言中的 switch ... case 语法,在多条件判断时比用 if ... elif 代码更简洁。

    下面看下match case的用法:

    def http_error(status):
        match status:
            case 400:
                return 'Bad Requests'
            case 404:
                return 'Not Found'
            case _:
                return 'other error'
    
    print(http_error(400))
    print(http_error(404))
    print(http_error(500))

    输出结果:

    Bad Requests

    Not Found

    other error

    case _  类似于其它语言中的 default ,当其他条件都不符合就执行这行。

    也可以在case语句后面使用 | 去进行连接:

      case 401 | 403 | 404: 
             return "Not allowed"


      Python3.10版本的新特性介绍

      在以后封装测试脚本的时候,也可以用上这个功能喔:

      def send_requests_method(method):
          match method:
              case 'GET':
                  return send_get_requests()
              case 'POST':
                  return send_post_requests()
              case 'PUT':
                  return send_put_requests()
              case _:
                  pass

      3、新的类型联合操作符

      在以前的版本中,要针对一个函数的入参做多种类型支持的话,要用到Union:

      from typing import Union
      def square(number: Union[int, float]) -> Union[int, float]:
          return number ** 2

      现在有个新的语法糖“|”,叫联合操作符,可以让代码更简洁

        def square(number: int | float) -> int | float: 
           return number ** 2

        该操作符在函数 isinstance()和 issubclass() 也可以支持

          print( isinstance(1, int | str))
          print(issubclass(int, int | str))


          4、持带括号的上下文管理器

          比如之前读取文件的操作是这样的:

          with open('file1', 'r') as f1, open('file2', 'r') as f2:   
               print(f.read())

          在3.10版本中,可以用括号将多个上下文放在一起:

          
          with (
              open('run.py', 'r')  as f1,
              open('run.py', 'r') as f2
          ):
              pass

          但是目前这种写法在pycharm中可以会有标红的错误提示,但不影响实际运行。



          上一篇:测试从零开始-电商项目实战-用例设计篇No.1-[后台-用户列表]


          下一篇:通过Postman工具如何快速批量生成Python Pytest的测试脚本