What did Python 3.9 bring?

Original link: https://www.dongwm.com/post/python-3-9/

foreword

Recently, I will make up for the new features that are helpful to developers brought by each new version of Python. Today, let’s talk about Python 3.9. This version is very moderate, and there are not many valuable modifications, so it is only listed in one article.

Dictionary addition coalescing operator

In PEP 584 – Add Union Operators To dict , it is proposed to add two operators, merge (|) and update (|=) to dict

There are two common ways of merging 2 dictionaries in the past:

 In : a = { 'a' : 1 }  In : b = { 'b' : 1 }  In : { ** a , ** b } # Scheme 1, use **, Python 3.5 and above Out : { 'a' : 1 , 'b' : 1 }  In : c = a . copy () # Option 2, use update  In : c . update ( b ) # If a.update is used directly, the result of a will be directly modified 

Of course, there are some more tricky ones, especially the dict(list(x.items()) + list(y.items())) in the Python 2 stage.

Since Python 3.9 this can be implemented using the bitwise OR operator:

 In : a = { 'a' : 1 }  In : b = { 'b' : 1 }  In : a | b Out : { 'a' : 1 , 'b' : 1 } 

If you want to replace directly after merging, you can use the update (|=) operator:

 In : a Out : { 'a' : 1 }  In : a |= b # Equivalent to a.update(b)  In : a Out : { 'a' : 1 , 'b' : 1 } # directly replaced on a (in place) 

Added string methods for removing prefixes and suffixes

In PEP 616 – String methods to remove prefixes and suffixes , two new string methods, removeprefix and removesuffix , have been added. Whereas in the past you needed to implement it yourself:

 def removeprefix ( self : str , prefix : str , / ) -> str :     if self . startswith ( prefix ):         return self [ len ( prefix ):]     else :         return self [:]  def removesuffix ( self : str , suffix : str , / ) -> str :     if suffix and self . endswith ( suffix ):         return self [: - len ( suffix )]     else :         return self [:] 

Of course, the corresponding methods of bytes , bytearray and collections.UserString are also added.

My understanding of this function is that some improvements can be made to the code in CPython based on it.

Decorator syntax improvements

In previous versions, a decorator was an object that needed to be determined. It did not support some expression calculation scenarios, nor did it support anonymous functions as decorators. Here are two examples:

“` python
In : from dataclasses import dataclass
…: d = [dataclass]
…:
…: @d[0]
…: class A:
…: attr: int
…:
…: print(A)
…:
File “<ipython-input-1-cf77b251b3d6>”, line 4
@d[0]
^
SyntaxError: invalid syntax

In : @lambda func: lambda args: func( args )+1
…: def plus(a, b):
…: return a + b
File “<ipython-i…

Original: What does Python 3.9 bring?

This article is reprinted from: https://www.dongwm.com/post/python-3-9/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment