程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The latest PEP proposal is launched. Python will be launched with major updates. What new functions will it bring?

編輯:Python

Python Before launching any new features , All need to be done by PEP, namely Python Enhanced proposal (Python Enhancement Proposal) Overview of new features . therefore , understand PEP To know Python What updates might be made in the future . In this paper , We will discuss in detail the upcoming Python New proposal . We classify all proposals into the following categories , They are syntax changes 、 type annotation 、 debugging 、 Quality of life 、 Ecological improvement, etc .

Grammatical changes

The first proposal is PEP 671, It proposes a syntax for late binding parameter defaults . Even though Python Functions in can take other functions as arguments . however , Currently, it is not possible to set default values for such parameters . Usually null or sentinel ( Global constants ) Use as default value , But such help(function) Cannot use... On a parameter . therefore PEP 671 Use is described in =>( param=>func()) New syntax for specifying functions as default arguments .

 # Current solution:
_SENTINEL = object()
def func(param=_SENTINEL):
if param is _SENTINEL:
# default_param holds expected default value
param = default_param
# New solution:
def func(param=>default_param):
...

This change really works , But we should be careful to add new grammar symbols or make too many grammar changes . We're not sure if a minor improvement like this requires another assignment operator .

Another proposal related to syntax changes is PEP 654, It proposes to except* As a new syntax for throwing exception groups . The basic principle of doing this is Python The interpreter can only propagate one exception at a time , But sometimes it is necessary to propagate multiple unrelated exceptions when the stack is expanded . This may lead to asyncio Causes a concurrency error or multiple different exceptions thrown when the retry logic is executed , For example, an exception occurs when connecting to a remote host .

try:
some_file_operation()
except* OSError as eg:
for e in eg.exceptions:
print(type(e).__name__)
# FileNotFoundError
# FileExistsError
# IsADirectoryError
# PermissionError
# ...

type annotation

And then PEP 673 The proposal . This proposal does not involve typing Module related knowledge . for instance : Suppose you have a with set_name Methodical Person class , Able to return to self, The instance Person class . If the same... Is used later set_name Create subclass Employee, It returns an instance of the type Employee instead of Person class . This does not apply to today's type checking —— stay Python 3.10 in , The type checker identifies the return type in the subclass as the return type of the base class .PEP 673 It can help the type checker to correctly infer types :

class Person:
def set_name(self, name: str) -> Self:
self.name = name
return self

The PEP Will serve as a Python 3.11 The new features of version are introduced .

besides ,PEP Another type of variation is proposed , That is, any text string . At present, we cannot specify that the type of function parameters can be any literal string ( Only specific text strings can be used , for example Literal["foo"]). Many people don't think this is a big problem , You may even wonder why someone needs to specify that the parameter should be string, instead of (f-string) Or other interpolated strings . in fact , This mainly involves a security issue —— Parameter is literal To avoid injection attacks , Whether it's SQL/ Command injection or XSS etc. . Having this function enables sqlite Wait for the library to remind users when string interpolation should not be used , So it does have its uses .

debugging

PEP 669 Put forward to CPython monitor . It is mentioned in this proposal that CPython Low cost monitoring , This does not affect when running the debugger or parser Python Performance of . Consider that there will be no performance loss during basic commissioning , This is right Python Has little impact on users .

But this function is very useful in some cases , for example :

  • Debugging problems that can only be reproduced in a production environment without affecting application performance ;
  • Debug race conditions that will be affected by time ;
  • Debug while running the benchmark .

For those who want to improve Python Performance people , This function is very useful , Can facilitate commissioning and benchmark performance issues / Improved progress .

meanwhile ,PEP 678 Properties mentioned in __note__ Should be added to BaseException Class . This property can be used to hold additional debugging information that can be displayed as part of the backtrace .

try:
raise TypeError('Some error')
except Exception as e:
e.__note__ = 'Extra information'
raise
# Traceback (most recent call last):
# File "<stdin>", line 2, in <module>
# TypeError: Some error
# Extra information

As shown in the example above , This can work when the exception is thrown again . just as PEP 669 As mentioned in , This is also useful for libraries with retry logic , Be able to add additional information for each failure . Again , The test library can add more to debug errors , For example, variable name and value .

except PEP 669, Another related to debugging is PEP 657, It is mentioned in the proposal that Python Add extra data to each bytecode instruction of . This data can generate better backtracking information . At the same time, the proposal also suggests that API, Allow other tools ( Such as analyzers or static analysis tools ) Using data .

This proposal seems ordinary , But it's actually the most practical of all proposals , Because it can bring better backtracking information , It can greatly improve the readability and debugging experience of backtracking .

The ecological system

PEP 680 I suggest Python The standard library of supports parsing TOML Format , And this could lead to bootstrapping problem . besides , Include flake8 Popular tools, including, don't support TOML, Because of the lack of support in the standard library . therefore PEP 680 It is suggested that TOML Support adding to the standard library .

It is feasible to support common formats in the standard library , Especially those for Python Tools and ecosystems are very important formats . When can we support in the standard library YAML Well ?

The last proposal is PEP 661, And “ Sentinel value ” of . stay Python This kind of value cannot be created in . As mentioned earlier PEP 671 Shown , Sentinel value usually requires _something = object, and PEP 661 The specific specification of tag value is proposed for the standard library :

# Old:
_sentinel = object()
# New:
from sentinels import sentinel
some_name = sentinel("some_name")

That's all Python Some functions to be launched soon , What other functions will there be in the future ? Let's wait and see !

【 Reference material 】
https://martinheinz.dev/blog/67


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved