Python 10

  • PEP 623 — Deprecate and prepare for the removal of the wstr member in PyUnicodeObject.
  • PEP 604 — Allow writing union types as X | Y
  • PEP 612 — Parameter Specification Variables
  • PEP 626 — Precise line numbers for debugging and other tools.
  • PEP 618 — Add Optional Length-Checking To zip.
  • bpo-12782: Parenthesized context managers are now officially allowed.
  • PEP 632 — Deprecate distutils module.
  • PEP 613 — Explicit Type Aliases
  • PEP 634 — Structural Pattern Matching: Specification
  • PEP 635 — Structural Pattern Matching: Motivation and Rationale
  • PEP 636 — Structural Pattern Matching: Tutorial
  • PEP 644 — Require OpenSSL 1.1.1 or newer
  • PEP 624 — Remove Py_UNICODE encoder APIs
  • PEP 597 — Add optional EncodingWarning

PEP 623 624

623: Deprecates and prepares to delete the WSTR member in PyUnicodeObject. 624: Remove Py_UNICODE encoder API

C, skip

PEP 604

Allows the Union type written as X | Y

Before Python10, data types were identified for type checking.

from typing import Union


def fun9(var: Union[None.int.str]) - >str:
    Var can be None, or int, or STR.
    if var is None:
        return 'null'
    if isinstance(var, int) :return str(var)
    return var
Copy the code

Now in Python10, you can write it like this.

def fun10(var: None | int | str) - >str:
    if var is None:
        return 'null'
    if isinstance(var, int) :return str(var)
    return var
Copy the code

PEP 612

Parameter specification variable

ParamSpec

To put it simply, a decorator decorates different functions and does not explicitly specify parameter types, but expects code (parameter types) checks, much like generics in other languages (Java). Code checking is not possible before Python10, for example

Before Python10, type checking for arguments of type Callable could not be passed

from typing import Awaitable, Callable, TypeVar

R = TypeVar("R")


def add_logging(f: Callable[..., R]) - >Callable[..., Awaitable[R]]:
    "" "... "" ignore the check "" ignore the check ""
    def inner(*args: object, **kwargs: object) -> R:
        return f(*args, **kwargs)

    return inner


@add_logging
def takes_int_str(x: int, y: str) - >int:
    return x + 7


takes_int_str(1."A")
takes_int_str("B".2)  The code inspector did not detect a problem, but it is actually wrong, and will fail at runtime

Copy the code

In Python10, you can do this now

PyCharm currently reports errors in this code, but it will work fine.

Pylint doesn’t seem to be able to detect this right now either.

from typing import Awaitable, Callable, TypeVar, ParamSpec

P = ParamSpec("P")

R = TypeVar("R")


def add_logging(f: Callable[P, R]) - >Callable[P, Awaitable[R]]:
    "" "... "" ignore the check "" ignore the check ""

    def inner(*args: object, **kwargs: object) -> R:
        return f(*args, **kwargs)

    return inner


@add_logging
def takes_int_str(x: int, y: str) - >int:
    return x + 7


takes_int_str(1."A")
takes_int_str("B".2)  The code inspector will detect the problem as expected

Copy the code

Concatenate

Based on the above problem, if the decorator needs to extend function parameters, the code inspector cannot detect it, and may even report an error. Python10 could not handle this problem before, but Python10 added the Concatenate type in typing. To accommodate this, a simple code example is shown below, as described in PEP 612

from typing import Concatenate

def with_request(f: Callable[Concatenate[Request, P], R]) - >Callable[P, R]:
  def inner(*args: P.args, **kwargs: P.kwargs) -> R:
    return f(Request(), *args, **kwargs)
  return inner

@with_request
def takes_int_str(request: Request, x: int, y: str) - >int:
  # use request
  return x + 7

takes_int_str(1."A") # Accepted
takes_int_str("B".2) # Correctly rejected by the type checker
Copy the code

PEP 626

The exact line number for debugging and other tools.

The exact line number of the debug message.

PEP 618

Add optional length check to zip.

Python10 now adds a strict keyword argument to the zip function to enforce checks that the traversable objects are of uniform length, which the proposers say can cause hard-to-find errors if not checked.

# prior to Python10, an error is reported because the strict keyword argument is missing
The # Python10 version also returns an error because strict mode is enabled, but the iterables in the argument are of different lengths

for a,b in zip([1.2.3], ['a'.'b'], strict=True) :print(a, b)
Copy the code

bop 12782

Context managers with parentheses are now officially allowed.

Simply put, when using with to open multiple files, one line of code was too long, and a backslash was required for a newline, but that’s no longer the case, and parentheses are used instead.

# Although not "introduced" until Python 3.10, thanks to the new PEG parser,
# CPython accepts new syntax changes -- so we have a new feature that is fully compatible with 3.9
# source: https://towardsdatascience.com/whats-new-in-python-3-10-a757c6c69342
with (open('src.txt') as src,
        open('dest.txt'.'w') as dest):
    dest.write(src.read())
Copy the code

PEP 634 635 636

634: Structural Pattern Matching: Specification 635: Structural pattern Matching: Motivation and Rationale 636: Structural Pattern Matching: Tutorial

Pattern matching has been added to Python10, the equivalent of switch in other languages… Case structure

def fun10(var: None | int | str) - >str:
    match type(var).__name__:
        case 'NoneType':
            return 'null'
        case 'int':
            return str(var)
        case _:
            return var
See PEP 636 for more usage
Copy the code

PEP 644

OpenSSL 1.1.1 or later is required

slightly

PEP 597

Add optional EncodingWarning

slightly