Python 3.10 is officially released. Have you tried it yet?
This paper reference since Python official documentation: Python Release Python 3.10.0 | Python.org
Python3.10.0 was officially released on October 4, 2021, just in time for the National Day holiday. As a coders who did not move during the holidays, I naturally experienced the wave at the first time. Compared with previous releases, this release has the following major changes.
Ps: Want to see better typography? Access: funnysaltyfish. Making. IO / 2021/10/05 /…
New Union Type expression
The use of the new version has simplified the Union Type, instead more concise |
The old version:
from typing import Union
a: Union[int.str] = 1
Copy the code
New version:
a: str | int = 1
Copy the code
The two are completely equivalent:
Union[int.str] = =int | str # True
Copy the code
The changes are similar elsewhere:
# the 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)
# the old version:
# typing.List[typing.Union[str, int]]
typing.List[str | int]
list[str | int]
# the old version:
# typing.Dict[str, typing.Union[int, float]]
typing.Dict[str.int | float]
dict[str.int | float]
Copy the code
This feature is also available for isInstance and IsSubClass
# True
isinstance("FunnySaltyFish".int|str)
# True
issubclass(str.str|int)
Copy the code
Zip Select strict mode
Zip adds strict to the optional argument. When True, the two iterable entries passed to zip must be of the same length, otherwise ValueError is raised
Old version (and do not add this parameter), when the two lengths are different, the smaller length 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 the code
Set strict to True
#...
z = zip(names,numbers,strict=True)
#...D: \ \ projects \ python learn \ Py310 exploration. Pyin <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 the code
Context manager with parentheses
With can be put in parentheses
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 the code
Such as
import pathlib
p = pathlib.Path()
p1 = p/"text1.txt" # content: The content of text 1
p2 = p/"text2.txt" # Content: The 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")
# The contents of text 1
# The content of text 2
Copy the code
Explicit type alias
Use TypeAlias to explicitly annotate type aliases to improve readability
The old way:
x = int
def plus_int(a:x,b:x) -> x:
return a+b
Copy the code
As you can see, x’s are easy to confuse
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 the code
match… A case statement
Yes, switch-case is another language. Python finally provides support for switch-case
Complete syntax see: PEP 634 – Structural Pattern Matching: Specification | Python.org
A few examples:
Basic type matching:
day = 6
match day:
case 1:
print("Monday")
case 6 | 7:
print("Weekend")
case _ :
print("Other circumstances")
Copy the code
Subject: This is particularly useful when working with command-line arguments
""" @copyright : [FunnySaltyFish](https://funnysaltyfish.github.io) @date : 2021/10/05 21:08:42 """
command = "save 1.txt"
# try changing command to list/copy 1.txt 2
match command.split(""):
case ["list"] :print("List files ~")
case ["save", file_name]:
print(F "save the file to{file_name}")
case ["copy",source,target]:
print(F "copy{source} -> {target}")
Copy the code
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 whose ID happens to be 2")
case Student():
print(F "This is the student whose ID is{a.id}")
case Teacher():
print(F "This is the teacher, named{a.name}")
Copy the code
You can also match a dictionary:
d = {
"name" : "Bill".# zhang SAN
"age" : 18."hobby" : "Reading"
}
match d:
case {"name":"Zhang", **args}:
# ** Collect additional parameters
print("This is Joe.", args) {'age': 18, 'hobby': 'read '}
case {"name" : name , "age" : age, "hobby": hobby}:
print(F "I called{name}This year,{age}Years old, like{hobby}") My name is Li Si. I am 18 years old and like reading
Copy the code
For more complex uses, see PEP 635 — Structural Pattern Matching: Motivation and Rationale comment and PEP 636 | Python.org – Structural Pattern Matching: Tutorial | Python.org
More friendly error notification
Python now throws more explicit errors when your parentheses and quotes are not closed
str = "Unclosed STR File"D: \ \ projects \ python learn \ Py310 exploration. Py", line 90 str = "Not closedstr
^
SyntaxError: unterminated string literal (detected at line 90)
Copy the code
arr = [1.2.2.3
File "D: \ \ projects \ python learn \ Py310 exploration. Py." ", line 91
arr = [1.2.2.3
^
SyntaxError: '[' was never closed
Copy the code
Some other updates:
Distutils was abandoned
Setuptools is recommended
OpenSSL 1.1.1 or later is required
Remove the Py_UNICODE encoding API
WSTR of PyUnicodeObject is deprecated and will be removed later
To the end. Fishing for fish.
Author: FunnySaltyFish homepage: FunnySaltyFish. Making. IO /