On October 4, 2021, when the National Day holiday is full of people, Python officially Officially released Python 3 ten . As a stationary coder during the holiday, I naturally experienced a wave for the first time. Compared with the previous version, this version has the following major changes.
ps: want to see a better typesetting? visit: funnysaltyfish.github.io/2021/10/05/...
New Union Type expression
The new version simplifies the use of Union Type and changes it to a more concise one|
Old version:
from typing import Union a: Union[int, str] = 1 Copy code
New version:
a: str | int = 1 Copy code
They are completely equivalent:
Union[int, str] == int | str # True Copy code
Such changes are similar elsewhere:
# Old version: # def f(list: List[Union[int, str]], param: Optional[int]) -> Union[float, str] def f(list: List[int | str], param: int | None) -> float | str: pass f([1, "abc"], None) # Old version: # typing.List[typing.Union[str, int]] typing.List[str | int] list[str | int] # Old version: # typing.Dict[str, typing.Union[int, float]] typing.Dict[str, int | float] dict[str, int | float] Copy code
This feature can also be used for isinstance and issubclass
# True isinstance("FunnySaltyFish", int|str) # True issubclass(str, str|int) Copy code
zip optional strict mode
zip adds an optional parameter strict. When this option is True, the length of the two iteratable items passed into zip must be equal, otherwise ValueError will be thrown
In the old version (and without this parameter), when the length of the two is different, the smaller one shall prevail
names = ["a","b","c","d"] numbers = [1,2,3] z = zip(names,numbers) for each in z: print(each) # ('a', 1) # ('b', 2) # ('c', 3) Copy code
Set strict to True
# ... z = zip(names,numbers,strict=True) # ... d:\projects\python\learn\Py310 explore.py in <module> 3 numbers = [1,2,3] 4 z = zip(names,numbers,strict=True) ----> 5 for each in z: 6 print(each) ValueError: zip() argument 2 is shorter than argument 1 Copy code
Bracketed context manager
with can be bracketed
with (CtxManager() as example): ... with ( CtxManager1(), CtxManager2() ): ... with (CtxManager1() as example, CtxManager2()): ... with (CtxManager1(), CtxManager2() as example): ... with ( CtxManager1() as example1, CtxManager2() as example2 ): ... Copy code
as
import pathlib p = pathlib.Path() p1 = p/"text1.txt" # Content: content of text 1 p2 = p/"text2.txt" # Content of text: 2 with( p1.open(encoding="utf-8") as f1, p2.open(encoding="utf-8") as f2 ): print(f1.read(), f2.read(), sep="\n") # Content of text 1 # Content of text 2 Copy code
Explicit type alias
Use TypeAlias to explicitly label type aliases to improve readability
Old way:
x = int def plus_int(a:x,b:x) -> x: return a+b Copy code
As you can see, x is easily confused
New way: use TypeAlias to indicate that this is an alias
from typing import TypeAlias x : TypeAlias = int def plus_int(a:x,b:x) -> x: return a+b Copy code
match... case statement
Yes, it's the switch case of other languages. python finally provides support. It's still an enhanced version
For complete syntax, see: PEP 634 – Structural Pattern Matching: Specification | Python.org
For example:
Basic type matching:
day = 6 match day: case 1: print("Monday") case 6 | 7: print("weekend") case _ : print("Other situations") Copy code
subject: This is particularly useful when dealing with command line parameters
""" @copyright : [FunnySaltyFish](https://funnysaltyfish.github.io) @date : 2021/10/05 21:08:42 """ command = "save 1.txt" # Try changing the command to list / copy 1 txt 2. Txt to see the effect match command.split(" "): case ["list"]: print("List files~") case ["save", file_name]: print(f"Save file to {file_name}") case ["copy",source,target]: print(f"Copy {source} -> {target}") Copy code
You can also match objects:
class Person(): pass class Student(Person): def __init__(self, id: int) -> None: self.id = id class Teacher(Person): def __init__(self, name: str) -> None: self.name = name a = Student(1) # a = Student(2) # a = Teacher("FunnySaltyFish") match a: case Student(id = 2): print(f"This is a student, and id Exactly 2") case Student(): print(f"This is a student, id by{a.id}") case Teacher(): print(f"This is the teacher, Name is{a.name}") Copy code
Of course, you can also match the dictionary:
d = { "name" : "Li Si", # Zhang San "age" : 18, "hobby" : "read" } match d: case {"name":"Zhang San", **args}: # **Collect other parameters print("This is Zhang San", args) # This is three {'age': 18, 'hobby': 'reading'} case {"name" : name , "age" : age, "hobby": hobby}: print(f"My name is{name}, this year{age}year, like{hobby}") #My name is Li Si. I'm 18 years old. I like reading Copy code
More complex is the combination of Guard and matching capture. For details, see: PEP 635 – Structural Pattern Matching: Motivation and Rationale | Python.org and PEP 636 – Structural Pattern Matching: Tutorial | Python.org
More friendly error reporting prompt
Now, when your parentheses and quotation marks are not closed, python will throw a clearer error
str = "Unclosed str File "d:\projects\python\learn\Py310 explore.py", line 90 str = "Unclosed str ^ SyntaxError: unterminated string literal (detected at line 90) Copy code
arr = [1, 2, 2, 3 File "d:\projects\python\learn\Py310 explore.py", line 91 arr = [1, 2, 2, 3 ^ SyntaxError: '[' was never closed Copy code
Other updates:
distutils is deprecated
setuptools is recommended
OpenSSL Version 1.1.1 and above is required
Remove Py_UNICODE encoding API
The wstr for pyunicode object is deprecated and will be removed later
End. Went fishing.