A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.python.org/3/whatsnew/3.11.html below:

What’s New In Python 3.11 — Python 3.13.5 documentation

What’s New In Python 3.11¶
Editor:

Pablo Galindo Salgado

This article explains the new features in Python 3.11, compared to 3.10. Python 3.11 was released on October 24, 2022. For full details, see the changelog.

Summary – Release highlights¶

New syntax features:

New built-in features:

New standard library modules:

Interpreter improvements:

New typing features:

Important deprecations, removals and restrictions:

New Features¶ PEP 657: Fine-grained error locations in tracebacks¶

When printing tracebacks, the interpreter will now point to the exact expression that caused the error, instead of just the line. For example:

Traceback (most recent call last):
  File "distance.py", line 11, in <module>
    print(manhattan_distance(p1, p2))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "distance.py", line 6, in manhattan_distance
    return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)
                           ^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'x'

Previous versions of the interpreter would point to just the line, making it ambiguous which object was None. These enhanced errors can also be helpful when dealing with deeply nested dict objects and multiple function calls:

Traceback (most recent call last):
  File "query.py", line 37, in <module>
    magic_arithmetic('foo')
  File "query.py", line 18, in magic_arithmetic
    return add_counts(x) / 25
           ^^^^^^^^^^^^^
  File "query.py", line 24, in add_counts
    return 25 + query_user(user1) + query_user(user2)
                ^^^^^^^^^^^^^^^^^
  File "query.py", line 32, in query_user
    return 1 + query_count(db, response['a']['b']['c']['user'], retry=True)
                               ~~~~~~~~~~~~~~~~~~^^^^^
TypeError: 'NoneType' object is not subscriptable

As well as complex arithmetic expressions:

Traceback (most recent call last):
  File "calculation.py", line 54, in <module>
    result = (x / y / z) * (a / b / c)
              ~~~~~~^~~
ZeroDivisionError: division by zero

Additionally, the information used by the enhanced traceback feature is made available via a general API, that can be used to correlate bytecode instructions with source code location. This information can be retrieved using:

See PEP 657 for more details. (Contributed by Pablo Galindo, Batuhan Taskaya and Ammar Askar in bpo-43950.)

Note

This feature requires storing column positions in Code Objects, which may result in a small increase in interpreter memory usage and disk usage for compiled Python files. To avoid storing the extra information and deactivate printing the extra traceback information, use the -X no_debug_ranges command line option or the PYTHONNODEBUGRANGES environment variable.

PEP 654: Exception Groups and except*¶

PEP 654 introduces language features that enable a program to raise and handle multiple unrelated exceptions simultaneously. The builtin types ExceptionGroup and BaseExceptionGroup make it possible to group exceptions and raise them together, and the new except* syntax generalizes except to match subgroups of exception groups.

See PEP 654 for more details.

(Contributed by Irit Katriel in bpo-45292. PEP written by Irit Katriel, Yury Selivanov and Guido van Rossum.)

PEP 678: Exceptions can be enriched with notes¶

The add_note() method is added to BaseException. It can be used to enrich exceptions with context information that is not available at the time when the exception is raised. The added notes appear in the default traceback.

See PEP 678 for more details.

(Contributed by Irit Katriel in bpo-45607. PEP written by Zac Hatfield-Dodds.)

Windows py.exe launcher improvements¶

The copy of the Python Launcher for Windows included with Python 3.11 has been significantly updated. It now supports company/tag syntax as defined in PEP 514 using the -V:<company>/<tag> argument instead of the limited -<major>.<minor>. This allows launching distributions other than PythonCore, the one hosted on python.org.

When using -V: selectors, either company or tag can be omitted, but all installs will be searched. For example, -V:OtherPython/ will select the “best” tag registered for OtherPython, while -V:3.11 or -V:/3.11 will select the “best” distribution with tag 3.11.

When using the legacy -<major>, -<major>.<minor>, -<major>-<bitness> or -<major>.<minor>-<bitness> arguments, all existing behaviour should be preserved from past versions, and only releases from PythonCore will be selected. However, the -64 suffix now implies “not 32-bit” (not necessarily x86-64), as there are multiple supported 64-bit platforms. 32-bit runtimes are detected by checking the runtime’s tag for a -32 suffix. All releases of Python since 3.5 have included this in their 32-bit builds.

Other Language Changes¶ Other CPython Implementation Changes¶ New Modules¶ Improved Modules¶ asyncio¶ contextlib¶ dataclasses¶ datetime¶ enum¶ fcntl¶ fractions¶ functools¶ gzip¶ hashlib¶ IDLE and idlelib¶ inspect¶ locale¶ logging¶ math¶ operator¶ os¶ pathlib¶ re¶ shutil¶ socket¶ sqlite3¶ string¶ sys¶ sysconfig¶ tempfile¶ threading¶ time¶ tkinter¶ traceback¶ typing¶

For major changes, see New Features Related to Type Hints.

unicodedata¶ unittest¶ venv¶ warnings¶ zipfile¶ Optimizations¶

This section covers specific optimizations independent of the Faster CPython project, which is covered in its own section.

Faster CPython¶

CPython 3.11 is an average of 25% faster than CPython 3.10 as measured with the pyperformance benchmark suite, when compiled with GCC on Ubuntu Linux. Depending on your workload, the overall speedup could be 10-60%.

This project focuses on two major areas in Python: Faster Startup and Faster Runtime. Optimizations not covered by this project are listed separately under Optimizations.

Faster Startup¶ Frozen imports / Static code objects¶

Python caches bytecode in the __pycache__ directory to speed up module loading.

Previously in 3.10, Python module execution looked like this:

Read __pycache__ -> Unmarshal -> Heap allocated code object -> Evaluate

In Python 3.11, the core modules essential for Python startup are “frozen”. This means that their Code Objects (and bytecode) are statically allocated by the interpreter. This reduces the steps in module execution process to:

Statically allocated code object -> Evaluate

Interpreter startup is now 10-15% faster in Python 3.11. This has a big impact for short-running programs using Python.

(Contributed by Eric Snow, Guido van Rossum and Kumar Aditya in many issues.)

Faster Runtime¶ Cheaper, lazy Python frames¶

Python frames, holding execution information, are created whenever Python calls a Python function. The following are new frame optimizations:

Old-style frame objects are now created only when requested by debuggers or by Python introspection functions such as sys._getframe() and inspect.currentframe(). For most user code, no frame objects are created at all. As a result, nearly all Python functions calls have sped up significantly. We measured a 3-7% speedup in pyperformance.

(Contributed by Mark Shannon in bpo-44590.)

Inlined Python function calls¶

During a Python function call, Python will call an evaluating C function to interpret that function’s code. This effectively limits pure Python recursion to what’s safe for the C stack.

In 3.11, when CPython detects Python code calling another Python function, it sets up a new frame, and “jumps” to the new code inside the new frame. This avoids calling the C interpreting function altogether.

Most Python function calls now consume no C stack space, speeding them up. In simple recursive functions like fibonacci or factorial, we observed a 1.7x speedup. This also means recursive functions can recurse significantly deeper (if the user increases the recursion limit with sys.setrecursionlimit()). We measured a 1-3% improvement in pyperformance.

(Contributed by Pablo Galindo and Mark Shannon in bpo-45256.)

PEP 659: Specializing Adaptive Interpreter¶

PEP 659 is one of the key parts of the Faster CPython project. The general idea is that while Python is a dynamic language, most code has regions where objects and types rarely change. This concept is known as type stability.

At runtime, Python will try to look for common patterns and type stability in the executing code. Python will then replace the current operation with a more specialized one. This specialized operation uses fast paths available only to those use cases/types, which generally outperform their generic counterparts. This also brings in another concept called inline caching, where Python caches the results of expensive operations directly in the bytecode.

The specializer will also combine certain common instruction pairs into one superinstruction, reducing the overhead during execution.

Python will only specialize when it sees code that is “hot” (executed multiple times). This prevents Python from wasting time on run-once code. Python can also de-specialize when code is too dynamic or when the use changes. Specialization is attempted periodically, and specialization attempts are not too expensive, allowing specialization to adapt to new circumstances.

(PEP written by Mark Shannon, with ideas inspired by Stefan Brunthaler. See PEP 659 for more information. Implementation by Mark Shannon and Brandt Bucher, with additional help from Irit Katriel and Dennis Sweeney.)

Operation

Form

Specialization

Operation speedup (up to)

Contributor(s)

Binary operations

x + x

x - x

x * x

Binary add, multiply and subtract for common types such as int, float and str take custom fast paths for their underlying types.

10%

Mark Shannon, Donghee Na, Brandt Bucher, Dennis Sweeney

Subscript

a[i]

Subscripting container types such as list, tuple and dict directly index the underlying data structures.

Subscripting custom __getitem__() is also inlined similar to Inlined Python function calls.

10-25%

Irit Katriel, Mark Shannon

Store subscript

a[i] = z

Similar to subscripting specialization above.

10-25%

Dennis Sweeney

Calls

f(arg)

C(arg)

Calls to common builtin (C) functions and types such as len() and str directly call their underlying C version. This avoids going through the internal calling convention.

20%

Mark Shannon, Ken Jin

Load global variable

print

len

The object’s index in the globals/builtins namespace is cached. Loading globals and builtins require zero namespace lookups.

[1]

Mark Shannon

Load attribute

o.attr

Similar to loading global variables. The attribute’s index inside the class/object’s namespace is cached. In most cases, attribute loading will require zero namespace lookups.

[2]

Mark Shannon

Load methods for call

o.meth()

The actual address of the method is cached. Method loading now has no namespace lookups – even for classes with long inheritance chains.

10-20%

Ken Jin, Mark Shannon

Store attribute

o.attr = z

Similar to load attribute optimization.

2% in pyperformance

Mark Shannon

Unpack Sequence

*seq

Specialized for common containers such as list and tuple. Avoids internal calling convention.

8%

Brandt Bucher

Misc¶ FAQ¶ How should I write my code to utilize these speedups?¶

Write Pythonic code that follows common best practices; you don’t have to change your code. The Faster CPython project optimizes for common code patterns we observe.

Will CPython 3.11 use more memory?¶

Maybe not; we don’t expect memory use to exceed 20% higher than 3.10. This is offset by memory optimizations for frame objects and object dictionaries as mentioned above.

I don’t see any speedups in my workload. Why?¶

Certain code won’t have noticeable benefits. If your code spends most of its time on I/O operations, or already does most of its computation in a C extension library like NumPy, there won’t be significant speedups. This project currently benefits pure-Python workloads the most.

Furthermore, the pyperformance figures are a geometric mean. Even within the pyperformance benchmarks, certain benchmarks have slowed down slightly, while others have sped up by nearly 2x!

Is there a JIT compiler?¶

No. We’re still exploring other optimizations.

About¶

Faster CPython explores optimizations for CPython. The main team is funded by Microsoft to work on this full-time. Pablo Galindo Salgado is also funded by Bloomberg LP to work on the project part-time. Finally, many contributors are volunteers from the community.

CPython bytecode changes¶

The bytecode now contains inline cache entries, which take the form of the newly-added CACHE instructions. Many opcodes expect to be followed by an exact number of caches, and instruct the interpreter to skip over them at runtime. Populated caches can look like arbitrary instructions, so great care should be taken when reading or modifying raw, adaptive bytecode containing quickened data.

New opcodes¶ Replaced opcodes¶

Replaced Opcode(s)

New Opcode(s)

Notes

BINARY_*

INPLACE_*

BINARY_OP

Replaced all numeric binary/in-place opcodes with a single opcode

CALL_FUNCTION

CALL_FUNCTION_KW

CALL_METHOD

CALL

KW_NAMES

PRECALL

PUSH_NULL

Decouples argument shifting for methods from handling of keyword arguments; allows better specialization of calls

DUP_TOP

DUP_TOP_TWO

ROT_TWO

ROT_THREE

ROT_FOUR

ROT_N

COPY SWAP

Stack manipulation instructions

JUMP_IF_NOT_EXC_MATCH

CHECK_EXC_MATCH

Now performs check but doesn’t jump

JUMP_ABSOLUTE

POP_JUMP_IF_FALSE

POP_JUMP_IF_TRUE

JUMP_BACKWARD

POP_JUMP_BACKWARD_IF_*

POP_JUMP_FORWARD_IF_*

See [3]; TRUE, FALSE, NONE and NOT_NONE variants for each direction

SETUP_WITH

SETUP_ASYNC_WITH

BEFORE_WITH

with block setup

Changed/removed opcodes¶ Deprecated¶

This section lists Python APIs that have been deprecated in Python 3.11.

Deprecated C APIs are listed separately.

Language/Builtins¶ Modules¶ Standard Library¶ Pending Removal in Python 3.12¶

The following Python APIs have been deprecated in earlier Python releases, and will be removed in Python 3.12.

C APIs pending removal are listed separately.

Removed¶

This section lists Python APIs that have been removed in Python 3.11.

Removed C APIs are listed separately.

Porting to Python 3.11¶

This section lists previously described changes and other bugfixes in the Python API that may require changes to your Python code.

Porting notes for the C API are listed separately.

Build Changes¶ C API Changes¶ New Features¶ Porting to Python 3.11¶ Deprecated¶ Pending Removal in Python 3.12¶

The following C APIs have been deprecated in earlier Python releases, and will be removed in Python 3.12.

Removed¶ Notable changes in 3.11.4¶ tarfile¶ Notable changes in 3.11.5¶ OpenSSL¶

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4