Release of the Python 3.10 programming language

After a year of development, a significant release of the Python 3.10 programming language is introduced. The new branch will be supported for a year and a half, after which patches with vulnerabilities will be formed for it for another three and a half years.

At the same time, alpha testing of the Python 3.11 branch began (in accordance with the new development schedule, work on a new branch begins five months before the release of the previous branch and reaches the alpha testing stage by the time of the next release). The Python 3.11 branch will be in alpha releases for seven months, during which new features will be added and bugs will be fixed. After that, beta testing will be conducted for three months, during which the addition of new features will be prohibited and all attention will be paid to fixing bugs. The last two months before the release, the branch will be at the release candidate stage, at which the final stabilization will be performed.

New additions in Python 3.10 include:

  • The "match" and "case" operators for pattern matching have been implemented to improve code readability, make it easier to match arbitrary Python objects, and improve code reliability with advanced static type checking. The implementation is much like the "match" operator provided in Scala, Rust, and F#, which compares the result of executing a specified expression against a list of patterns listed in blocks based on the "case" operator.

    def http_error(status): match status: case 400: return "Bad request" case 401|403|404: return "Not allowed" case 418: return "I'm a teapot" case _: return "Something else"

    It is possible to unpack objects, tuples, lists, and arbitrary sequences to bind variables based on available values. It is allowed to define nested templates, use additional "if" conditions in the template, use masks ("[x, y, *rest]"), mapping key/value bindings (for example, {"bandwidth": b, "latency": l} to extract the "bandwidth" and "latency" values ​​from the dictionary), extracting subpatterns (the ":=" operator), using named constants in the template. In classes, it is possible to customize the matching behavior using the "__match__()" method.

    from dataclasses import dataclass @dataclass class Point: x: int y: int def whereis(point): match point: case Point(0, 0): print("Origin") case Point(0, y): print(f" Y={y}") case Point(x, 0): print(f"X={x}") case Point(): print("Somewhere else") case _: print("Not a point") match point: case Point(x, y) if x == y: print(f"Y=X at {x}") case Point(x, y): print(f"Not on the diagonal") RED, GREEN, BLUE = 0, 1, 2 match color: case RED: print("I see red!") case GREEN: print("Grass is green") case BLUE: print("I'm feeling the blues :(")

  • Provided the ability to use parentheses in the with statement to span across multiple lines the definition of a collection of context managers. It is also allowed to leave a comma after the final context manager in a group: with ( CtxManager1() as example1, CtxManager2() as example2, CtxManager3() as example3, ): …
  • Improved code location reporting for errors related to unclosed curly braces and quotes in string literals. For example, with an unclosed curly brace, instead of reporting a syntax error in the following construct, the pointer now highlights the opening curly brace and informs about the absence of a closing block. File "example.py", line 1 expected = {9:1, 18:2, 19:2, 27:3, 28:3, 29:3, 36:4, 37:4, ^SyntaxError: '{' was never closed

    Added additional specialized syntax error messages: missing ":" symbol before a block and in dictionaries, not selecting a tuple with brackets, missing a comma in lists, specifying a "try" block without "except" and "finally", using "=" instead of "= =" in comparisons, specifying *-expressions in f-strings. In addition, the selection of the entire problematic expression, and not just its beginning, is provided, and more explicit information about the context of errors associated with incorrect indentation. >>> def foo(): ... if lel: ... x = 2 File " ”, line 3 x = 2 ^ IndentationError: expected an indented block after 'if' statement in line 2

    In errors caused by typos in the names of attributes and variable names in a function, the output of the recommendation with the correct name is ensured. >>> collections.namedtoplo Traceback (most recent call last): File " ”, line 1, in AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple?

  • For debugging tools and profilers, the exact line numbers of the executed code are specified in the trace events.
  • Added setting sys.flags.warn_default_encoding to warn about potential errors related to TextIOWrapper and open() handling UTF-8 encoded files without explicitly specifying the 'encoding="utf-8β€³' option (ASCII encoding is used by default). Also in the new release is the ability to specify the value 'encoding="locale"' to set the encoding based on the current locale.
  • A new operator has been added to the typing module, which provides tools for specifying type annotations, to allow the use of the "X | Y” to select one of the types (type X or type Y). def square(number: int | float) -> int | float: return number ** 2 is equivalent to the previously supported construct: def square(number: Union[int, float]) -> Union[int, float]: return number ** 2
  • Added a Concatenate statement and a ParamSpec variable to the typing module to allow additional information to be passed for static type checking when using Callable. Also added to the typing module are special TypeGuard values ​​to annotate type protection functions and TypeAlias ​​to explicitly define a type alias. StrCache: TypeAlias ​​= 'Cache[str]' # a type alias
  • The zip() function implements an optional "strict" flag, which, if specified, checks for the same length of the iterated arguments. >>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True)) [('a', 1), ('b', 2) , ('c', 3)] >>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True)) Traceback (most recent call last ): ... ValueError: zip() argument 2 is longer than argument 1
  • New built-in functions aiter() and anext() are proposed with the implementation of asynchronous analogues to the functions iter() and next().
  • The work of the str(), bytes() and bytearray() constructors has been accelerated by 30-40% when working with small objects.
  • Reduced the number of imports in the runpy module. The "python3 -m modulename" command now runs 1.4x faster on average by reducing imported modules from 69 to 51.
  • The LOAD_ATTR instruction uses a mechanism for caching individual opcodes, which made it possible to speed up work with ordinary attributes up to 36%, and with slots up to 44%.
  • When building Python with the "--enable-optimizations" option, the "-fno-semantic-interposition" mode is now enabled, which, compared to building with the "--enable-shared" option, speeds up the interpreter by up to 30%.
  • Added support for OpenSSL 3.0.0 in hashlib and ssl modules and removed support for OpenSSL versions older than 1.1.1.
  • The old parser has been removed, which was replaced by the PEG (Parsing Expression Grammar) parser in the last branch. Removed formatter module. The loop parameter has been removed from the asyncio API. Methods previously deprecated have been removed. Removed Py_UNICODE_str* functions that manipulate Py_UNICODE* strings.
  • The distutils module has been deprecated and is scheduled for removal in Python 3.12. Instead of distutils, it is recommended to use the setuptools, packaging, platform, shutil, subprocess and sysconfig modules. Moved the wstr structure to PyUnicodeObject as deprecated and slated for deletion.

Source: opennet.ru

Add a comment