Releasecore
Python 3.11
Python 3.11 came out on 2022-10-24. It is 1.25 times faster than 3.10 on average, and it adds exception groups, exception notes, tomllib and exact error locations in tracebacks.
- Language
- Python
- Version
- 3.11
- Released
- 2022-10-24
- End of life
- 2027-10
What is new
Python 3.11.0 was released on 2022-10-24. It is between 10 and 60 percent faster than 3.10, and 1.25 times faster on average on the standard benchmark suite.1 It adds a way to raise and handle several exceptions at once, notes on exceptions, a TOML parser, and tracebacks that point to the exact expression. The examples on this page ran on CPython 3.11.18, 3.12, 3.13.18, 3.14.10 and 3.15.2, with the same output. Most of them fail on 3.10.
Faster CPython
The Faster CPython project made 3.11 about 25 percent faster than 3.10 on pyperformance, built with GCC on Ubuntu Linux. Start-up is 10 to 15 percent faster because the core modules are frozen into the interpreter. Frames are cheaper, and frame objects are made only when a debugger or an introspection function asks for them. Most calls from Python code to a Python function use no C stack space.10
PEP 659 adds the specializing adaptive interpreter. When code runs many times, the interpreter replaces a generic bytecode instruction with a specialized one for the types it sees, and it caches results inline in the bytecode.8 A try statement costs nothing when no exception is raised.10 See the specializing adaptive interpreter.
Exception groups and except* (PEP 654)
The built-in types ExceptionGroup and BaseExceptionGroup carry several unrelated exceptions together. The new except* clause handles the part of a group that matches a type, and passes the rest on.4 This is for code that runs many tasks and must report every failure, such as asyncio.TaskGroup.
def check(values):
errors = []
for v in values:
try:
if not isinstance(v, int):
raise TypeError(f"not an int: {v!r}")
if v < 0:
raise ValueError(f"negative: {v}")
except (TypeError, ValueError) as error:
errors.append(error)
if errors:
raise ExceptionGroup("bad values", errors)
try:
check([1, -2, "x", -3])
except* ValueError as group:
print("ValueError:", [str(e) for e in group.exceptions])
except* TypeError as group:
print("TypeError:", [str(e) for e in group.exceptions])
ValueError: ['negative: -2', 'negative: -3']
TypeError: ["not an int: 'x'"]
See raising and handling multiple unrelated exceptions.
Exception notes (PEP 678)
BaseException.add_note() adds a string to the list __notes__ of an exception. The traceback prints each note after the message.5 This lets code add context to an exception without a new exception type.
import traceback
try:
try:
int("x1")
except ValueError as error:
error.add_note("while reading line 7 of settings.txt")
raise
except ValueError as error:
print(error.__notes__)
print("".join(traceback.format_exception_only(error)), end="")
['while reading line 7 of settings.txt']
ValueError: invalid literal for int() with base 10: 'x1'
while reading line 7 of settings.txt
See enriching exceptions with notes.
tomllib (PEP 680)
The new module tomllib reads TOML, the format of pyproject.toml. It can only parse; it cannot write TOML.6
import tomllib
text = """
[project]
name = "demo"
version = "1.0"
dependencies = ["requests>=2", "rich"]
"""
data = tomllib.loads(text)
print(data["project"]["name"], data["project"]["dependencies"])
demo ['requests>=2', 'rich']
Fine-grained error locations (PEP 657)
A traceback now marks the exact expression that failed, not only the line. In a line with several subscripts or calls, this shows which one raised the error.7
import traceback
def total(order):
return order["price"] * order["count"] + order["tax"]["rate"]
try:
total({"price": 2, "count": 3, "tax": None})
except TypeError:
for line in traceback.format_exc().splitlines()[-3:]:
print(line)
return order["price"] * order["count"] + order["tax"]["rate"]
~~~~~~~~~~~~^^^^^^^^
TypeError: 'NoneType' object is not subscriptable
The positions are in code objects, and codeobject.co_positions() returns them. The option -X no_debug_ranges and the variable PYTHONNODEBUGRANGES turn the feature off, to save a little memory and disk space.1 See tracebacks and exception objects.
Typing
- PEP 673:
typing.Selfis the type of the current instance, for methods that returnselfor a copy of it.9 - PEP 646: variadic generics, with
TypeVarTuple, for types such as array shapes.12 - PEP 655:
RequiredandNotRequiredmark single items of aTypedDict.12 - PEP 675:
LiteralStringaccepts only strings that come from literals, to guard against injection.12 - PEP 681:
dataclass_transformmarks a decorator or a base class that makes classes likedataclassesdoes.12 - PEP 563, which turns all annotations into strings, was planned to become the default. That plan is on hold indefinitely.12 Later, Python 3.14 made the evaluation of annotations lazy instead.
from typing import Self
class Shape:
def scaled(self, k: float) -> Self:
clone = type(self).__new__(type(self))
clone.__dict__ = {key: v * k for key, v in self.__dict__.items()}
return clone
class Square(Shape):
def __init__(self, side):
self.side = side
print(type(Square(2).scaled(3)).__name__, Square(2).scaled(3).side)
Square 6
Smaller language and library changes
- The format option
zturns a negative zero into a positive zero after rounding (PEP 682).11 - A starred expression can be the iterable of a
forstatement, as infor x in *a, *b:.11 - The option
-Pand the variablePYTHONSAFEPATHstop Python from adding the directory of the script, or the current directory, tosys.path. So a local file cannot shadow a module of the standard library.11 - A
withstatement on an object that is not a context manager raisesTypeError, notAttributeError.11 - The conversion between
intandstrin base 10 and other bases that are not a power of two raisesValueErrorabove 4300 digits, by default. This mitigates CVE-2020-10735, a denial of service.sys.set_int_max_str_digits()changes the limit.19
import sys
print(f"{-0.0001:.2f}", f"{-0.0001:z.2f}")
print(sys.get_int_max_str_digits())
try:
int("1" * 5000)
except ValueError as error:
print(str(error).split(";")[0])
seen = []
for x in *[1, 2], *[3]:
seen.append(x)
print(seen)
-0.00 0.00
4300
Exceeds the limit (4300 digits) for integer string conversion: value has 5000 digits
[1, 2, 3]
Removed and deprecated
Removed in 3.11
Most items below were deprecated in an earlier release.14
- The decorator
@asyncio.coroutine, for generator-based coroutines. Useasync def. - The module
binhex, and the related functions ofbinasciisuch asa2b_hqx(). - In
inspect:getargspec()andformatargspec(). Useinspect.signature(). - In
gettext:lgettext(),ldgettext(),lngettext()andldngettext(), and thecodesetparameter. - The mode
'U'ofopen(),io.open(),codecs.open()andfileinput.FileInput. Text mode always uses universal newlines.15 - The
reuse_addressparameter ofasyncio.loop.create_datagram_endpoint(), for security reasons. - The
__getitem__()methods ofxml.dom.pulldom.DOMEventStream,wsgiref.util.FileWrapperandfileinput.FileInput. - Namespace package support in
unittestdiscovery.
Deprecated in 3.11
The version in brackets is the planned removal.13
- PEP 594: the 19 modules
aifc,audioop,cgi,cgitb,chunk,crypt,imghdr,mailcap,msilib,nis,nntplib,ossaudiodev,pipes,sndhdr,spwd,sunau,telnetlib,uuandxdrlib(3.13). asynchat,asyncoreandsmtpd(3.12).lib2to3and the2to3tool. They may not parse code for Python 3.10 or newer.- The undocumented modules
sre_compile,sre_constantsandsre_parse. - Chained
classmethoddescriptors. - Octal escapes above
0o377, such as"\477". int()on an object that has only__trunc__().locale.getdefaultlocale()(3.15) andlocale.resetlocale()(3.13).re.template()andre.TEMPLATE(3.13).typing.Text, and the keyword-argument form ofTypedDict(3.13).- The old functions of
importlib.resources, such asopen_text()andread_binary(). configparser.LegacyInterpolation(3.13), and the oldconfigparsernamesSafeConfigParserandreadfp()(3.12).
Migration
Most code that runs on 3.10 without warnings runs on 3.11. These changes can break it.15
- File mode.
open(name, "rU")raisesValueError. Remove theU. - random. The population of
random.sample()must be a sequence. A set is no longer converted. A sample larger than the population raisesValueError. - asyncio.
@asyncio.coroutineis gone, andloop.set_default_executor()accepts only aThreadPoolExecutor. - ast.
compile()checks the positions ofastnodes and raisesValueErrorfor invalid ones. - Integer strings. A program that converts very long numbers between
intandstrin base 10 fails withValueErrorabove 4300 digits. Raise the limit withsys.set_int_max_str_digits(), the option-X int_max_str_digitsor the variablePYTHONINTMAXSTRDIGITS.19 - object.getstate(). The new default method can confuse code that tests whether
__getstate__exists.11 - Deprecations. Run the test suite with
-W error::DeprecationWarningto find uses of the PEP 594 modules, which 3.13 removes.
Several bugfix releases changed behaviour.16 3.11.4 adds the filter argument to the extraction methods of tarfile and to shutil.unpack_archive(). 3.11.5 builds the python.org Windows and macOS installers with OpenSSL 3.0. 3.11.10 fixes is_global and is_private in ipaddress, and makes email stricter about headers and addresses (CVE-2023-27043). 3.11.13 adds os.path.ALLOW_MISSING and fixes path traversal problems in the tarfile filters (CVE-2025-4435 and others). The security release 3.11.18 makes ssl reject certificate chains that contain one of a set of compromised eMudhra intermediate CA certificates.17
Support dates
The release manager of 3.11 is Pablo Galindo Salgado.2 CPython releases have two phases of support.3
| Phase | From | To |
|---|---|---|
| Bugfix (binary installers, regular releases) | 2022-10-24 | 2024-04-02 (3.11.9) |
| Security (source-only releases, as needed) | after 3.11.9 | October 2027 |
Development of 3.11 began on 2021-05-03. The first alpha came on 2021-10-05, beta 1 on 2022-05-08 and the first release candidate on 2022-08-08.2 3.11 had bugfix releases about every two months for about 18 months. 3.11.9, the ninth bugfix release, was the last one with binary installers. After it, security fixes come as source releases until about October 2027, five years after 3.11.0.2
The dates of the releases come from the changelog.18 PEP 664 gives other dates for three releases: 2023-02-08 for 3.11.2, 2023-04-05 for 3.11.3 and 2026-08-12 for 3.11.16.2
| Release | Date |
|---|---|
| 3.11.0 | 2022-10-24 |
| 3.11.1 | 2022-12-06 |
| 3.11.2 | 2023-02-07 |
| 3.11.3 | 2023-04-04 |
| 3.11.4 | 2023-06-06 |
| 3.11.5 | 2023-08-24 |
| 3.11.6 | 2023-10-02 |
| 3.11.7 | 2023-12-04 |
| 3.11.8 | 2024-02-06 |
| 3.11.9 | 2024-04-02 |
| 3.11.10 | 2024-09-07 |
| 3.11.11 | 2024-12-03 |
| 3.11.12 | 2025-04-08 |
| 3.11.13 | 2025-06-03 |
| 3.11.14 | 2025-10-09 |
| 3.11.15 | 2026-03-03 |
| 3.11.16 | 2026-08-13 |
| 3.11.17 | 2026-10-01 |
| 3.11.18 | 2026-10-25 |
References
- What's New In Python 3.11, Summary, release highlights
- PEP 664: Python 3.11 Release Schedule, Release schedule; Bugfix releases; 3.11 Lifespan
- Status of Python versions, Python Developer's Guide, Supported versions
- PEP 654: Exception Groups and except*, Specification
- PEP 678: Enriching Exceptions with Notes, Specification
- PEP 680: tomllib: Support for Parsing TOML in the Standard Library, Specification
- PEP 657: Include Fine Grained Error Locations in Tracebacks, Specification
- PEP 659: Specializing Adaptive Interpreter, Specialization
- PEP 673: Self Type, Specification
- What's New In Python 3.11, Faster CPython
- What's New In Python 3.11, Other Language Changes
- What's New In Python 3.11, New Features Related to Type Hints
- What's New In Python 3.11, Deprecated
- What's New In Python 3.11, Removed
- What's New In Python 3.11, Porting to Python 3.11
- What's New In Python 3.11, Notable Changes in 3.11.4, 3.11.5, 3.11.10 and 3.11.13
- What's New In Python 3.11, Notable changes in 3.11.18
- Changelog, Python 3.11 documentation, Python 3.11.18 final back to Python 3.11.0 final
- What's New In Python 3.11, Other CPython Implementation Changes
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag E8WVFT Edit this page History Report an error Markdown