Releasecore
Python 3.12
Python 3.12 came out on 2023-10-02. It adds the type parameter syntax, f-strings in the grammar, a per-interpreter GIL and sys.monitoring, and it removes distutils.
- Language
- Python
- Version
- 3.12
- Released
- 2023-10-02
- End of life
- 2028-10
What is new
Python 3.12.0 was released on 2023-10-02.1 Its largest changes are a new syntax for generic types, a formal grammar for f-strings and better "Did you mean" suggestions. The library drops distutils and several other old modules. The examples on this page ran on CPython 3.12, 3.13.18, 3.14.10 and 3.15.2. Most of them fail on 3.11.
Type parameter syntax (PEP 695)
A generic function or class can declare its type parameters in square brackets after its name, with no TypeVar call. The new type statement declares a type alias, whose value is evaluated lazily.4
def first[T](items: list[T]) -> T:
return items[0]
class Stack[T]:
def __init__(self) -> None:
self.items: list[T] = []
type Pair[T] = tuple[T, T]
print(first([3, 1, 2]))
print(first.__type_params__, Stack.__type_params__)
print(type(Pair).__name__, Pair.__value__, Pair.__type_params__)
3
(T,) (T,)
TypeAliasType tuple[T, T] (T,)
The type parameters live in a new kind of scope. See annotation scopes.
f-strings in the grammar (PEP 701)
The parser now reads f-strings with the grammar of the language, not with a separate routine. So the expression in a replacement field can reuse the quote of the f-string, contain a backslash, span several lines with comments, and nest without a limit on depth.5
songs = ["Eden", "Alkaline", "Ascensionism"]
print(f"Playlist: {", ".join(songs)}")
print(f"{"\n".join(songs)}")
print(f"{len([
1, # one
2, # two
])}")
print(f"{f"{f"{1 + 1}"}"}")
Playlist: Eden, Alkaline, Ascensionism
Eden
Alkaline
Ascensionism
2
2
On 3.11 the second line of this program is a SyntaxError. A side effect of the change is that the module tokenize emits new tokens for f-strings.15 See formatted string literals.
A per-interpreter GIL (PEP 684)
Each subinterpreter can now have its own global interpreter lock, so subinterpreters can run in parallel. In 3.12 this is available only through the C API.6 Python code got a module for it in 3.14. See subinterpreters and the global interpreter lock.
Low-impact monitoring (PEP 669)
The namespace sys.monitoring lets a debugger, a profiler or a coverage tool ask for events such as the start of a function, a line or a branch. A tool pays only for the events that it turns on, which is much cheaper than sys.settrace().7
import sys
mon = sys.monitoring
calls = []
def on_start(code, offset):
calls.append(code.co_name)
def square(n):
return n * n
mon.use_tool_id(mon.PROFILER_ID, "demo")
mon.register_callback(mon.PROFILER_ID, mon.events.PY_START, on_start)
mon.set_events(mon.PROFILER_ID, mon.events.PY_START)
square(2)
square(3)
mon.set_events(mon.PROFILER_ID, 0)
mon.free_tool_id(mon.PROFILER_ID)
print(calls)
['square', 'square']
Comprehension inlining (PEP 709)
List, dict and set comprehensions no longer create a new single-use function object each time they run. The interpreter inlines them, which makes a comprehension up to two times faster.8 A comprehension no longer appears as a separate frame in a traceback, and locals() in a comprehension now includes the variables from outside the comprehension.1 The loop variable of a comprehension stays local to it.
Better error messages
A NameError at the top level can suggest a standard module to import, and a NameError in a method can suggest self.<name>. The text import x from y gets a hint to write from y import x. A failed from module import name suggests a close name in the module.10
import traceback
try:
exec("from sys import getrecursionlimt")
except ImportError as error:
print(traceback.format_exception_only(error)[-1], end="")
ImportError: cannot import name 'getrecursionlimt' from 'sys' (unknown location). Did you mean: 'getrecursionlimit'?
On 3.11 the same program prints the message with no suggestion.
Typing
- PEP 692:
**kwargs: Unpack[Movie]types the keyword arguments of a function with aTypedDict, so each keyword can have its own type.12 - PEP 698: the decorator
typing.overridesays that a method overrides a method of a base class. A type checker reports an error when no base class has the method.12
Smaller language and library changes
- A backslash pair that is not a valid escape sequence, such as
"\d", givesSyntaxWarning, notDeprecationWarning. A later release will make it aSyntaxError. Use raw strings for regular expressions.11 sum()of floats uses Neumaier summation, which is more accurate.11sliceobjects are hashable, so they can be dict keys and set members.11itertools.batched(iterable, n)yields tuples ofnitems, and the last one can be shorter.1 See itertools.- The extraction methods of
tarfileandshutil.unpack_archive()take afilterargument, which can refuse dangerous members, such as a file outside the target directory.11 sqlite3anduuidhave a command-line interface, andpathlib.Pathsupports subclasses.1- CPython supports the Linux
perfprofiler, and it protects against stack overflow on the platforms that support it.1 - PEP 683 makes some objects immortal, so their reference counts never change. PEP 697 adds an unstable tier of the C API.1
import warnings
from itertools import batched
print(list(batched("ABCDEFG", 3)))
print(sum([0.1] * 10) == 1.0)
print({slice(1, 3): "middle"}[slice(1, 3)])
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
compile(r'pattern = "\d+"', "<demo>", "exec")
print(caught[0].category.__name__)
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
True
middle
SyntaxWarning
On 3.11, sum([0.1] * 10) == 1.0 is False, and the warning for "\d" is a DeprecationWarning:
import warnings
print(sum([0.1] * 10) == 1.0)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
compile(r'pattern = "\d+"', "<demo>", "exec")
print(caught[0].category.__name__)
False
DeprecationWarning
Removed and deprecated
Removed in 3.12
Most items below were deprecated in an earlier release.13
- The package
distutils(PEP 632). The third-party packagesetuptoolsstill provides it.9 venvno longer installssetuptoolsin a new environment, andensurepipno longer bundles it. Sosetuptools,pkg_resourcesandeasy_installare not there by default. Runpip install setuptoolsin the environment if a project needs them at run time.- The modules
asynchat,asyncoreandsmtpd(PEP 594). Useasyncio, or the PyPI packageaiosmtpdforsmtpd. - The module
imp. Useimportlib; the docs give a table of replacements. - The aliases of
unittest.TestCasemethods, such asassertEquals,failUnlessandassertRegexpMatches, andassertDictContainsSubset(). ssl.wrap_socket()andssl.match_hostname(). UseSSLContext.wrap_socket().locale.format(). Uselocale.format_string().- In
configparser:SafeConfigParserandreadfp(). UseConfigParserandread_file(). - The
keyfileandcertfileparameters offtplib,imaplib,poplibandsmtplib. Usecontext. importlibcleanups:find_loader()andfind_module()support,importlib.abc.Finder, andpkgutil.ImpImporter.io.OpenWrapper,sqlite3.enable_shared_cache()andsqlite3.OptimizedUnicode,gzip.GzipFile.filenameandssl.RAND_pseudo_bytes().- PEP 623: the C API no longer keeps a
wstrcopy of eachstrobject, which saves at least 8 bytes per string.1
import importlib.util
import unittest
print(hasattr(unittest.TestCase, "assertEquals"))
print(importlib.util.find_spec("imp"), importlib.util.find_spec("asyncore"))
False
None None
Deprecated in 3.12
The version in brackets is the planned removal.14
datetime.datetime.utcnow()andutcfromtimestamp(). Usenow(tz=datetime.UTC)andfromtimestamp(ts, tz=datetime.UTC).- The
astclassesNum,Str,Bytes,NameConstantandEllipsiswarn on use (3.14). Useast.Constant. - The asyncio child watchers (3.14).
asyncio.get_event_loop()warns when it has to make a loop. ~on abool(an error in 3.16). Usenot.- The
onerrorargument ofshutil.rmtree(). Useonexc. - Copy, deep copy and pickle of
itertoolsiterators (3.14). tarfileextraction with nofilter, until 3.14 makes'data'the default.sys.last_type,sys.last_valueandsys.last_traceback. Usesys.last_exc.- The three-argument form of
throw()on generators and coroutines. typing.Hashableandtyping.Sized, andcollections.abc.ByteString.calendar.Januaryandcalendar.February. UseJANUARYandFEBRUARY.- Setting
__package__or__cached__on a module (3.14). - In
sqlite3: the default adapters and converters, and named placeholders with a sequence of parameters (an error in 3.14). os.fork()in a process with several threads can warn, on POSIX.
Migration
Most code that runs on 3.11 without warnings runs on 3.12. These changes can break it.15
- distutils and setuptools.
import distutilsfails. A project that builds withsetup.pymust declaresetuptoolsas a build dependency, and a new virtual environment has nosetuptoolsunless you install it.13 - Removed modules. Code that imports
imp,asynchat,asyncoreorsmtpdfails withModuleNotFoundError. - unittest. Old test suites that call
assertEquals()and the other aliases fail withAttributeError. Rename the calls. - Escapes. Each invalid escape such as
"\d"in a normal string literal now prints aSyntaxWarningwhen the module compiles. Change the literal to a raw string. - random.
randrange(10.0)raisesTypeError, and non-integer arguments raiseTypeError, notValueError. - re. Numerical group references must be ASCII digits, and group names in bytes patterns must be ASCII letters, digits and underscores.
- os. Path functions accept only
bytesfor byte paths, notbytearrayormemoryview. - functools.cached_property. It no longer holds a lock, so two threads can both run the getter for one instance.
- tokenize. Tools that read tokens get the new f-string tokens.
Several bugfix releases changed behaviour for safety. 3.12.4 fixed is_global and is_private of ipaddress. 3.12.5 made the email generator refuse to write headers that would parse as more than one header. 3.12.6 made email.utils.getaddresses() and parseaddr() stricter, with a strict=False option for the old behaviour.16 The security release 3.12.11 fixed several ways to get around the tarfile extraction filters with crafted links.18 The security release 3.12.16 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.12 is Thomas Wouters.2 CPython releases have two phases of support.3
| Phase | From | To |
|---|---|---|
| Bugfix (binary installers, regular releases) | 2023-10-02 | 2025-04-08 (3.12.10) |
| Security (source-only releases, as needed) | after 3.12.10 | October 2028 |
Development of 3.12 began on 2022-05-08. The first alpha came on 2022-10-24, beta 1 on 2023-05-22 and the first release candidate on 2023-08-06.2 3.12 had bugfix releases for about 18 months. 3.12.10 was the tenth and last bugfix release with binary installers. After it, security fixes come as source releases until about October 2028, five years after 3.12.0.2 3.12 is one of the releases that PEP 602 gave one and a half years of bugfix support, before the policy grew to two years with 3.13.3
The dates of the releases come from the changelog, and they agree with PEP 693.18
| Release | Date |
|---|---|
| 3.12.0 | 2023-10-02 |
| 3.12.1 | 2023-12-07 |
| 3.12.2 | 2024-02-06 |
| 3.12.3 | 2024-04-09 |
| 3.12.4 | 2024-06-06 |
| 3.12.5 | 2024-08-06 |
| 3.12.6 | 2024-09-06 |
| 3.12.7 | 2024-10-01 |
| 3.12.8 | 2024-12-03 |
| 3.12.9 | 2025-02-04 |
| 3.12.10 | 2025-04-08 |
| 3.12.11 | 2025-06-03 |
| 3.12.12 | 2025-10-09 |
| 3.12.13 | 2026-03-03 |
| 3.12.14 | 2026-08-12 |
| 3.12.15 | 2026-10-01 |
| 3.12.16 | 2026-10-25 |
References
- What's New In Python 3.12, Summary, release highlights
- PEP 693: Python 3.12 Release Schedule, Release schedule; Bugfix releases; 3.12 Lifespan
- Status of Python versions, Python Developer's Guide, Supported versions
- PEP 695: Type Parameter Syntax, Specification
- PEP 701: Syntactic formalization of f-strings, Specification
- PEP 684: A Per-Interpreter GIL, Specification
- PEP 669: Low Impact Monitoring for CPython, Specification
- PEP 709: Inlined comprehensions, Specification
- PEP 632: Deprecate distutils module, Migration Advice
- What's New In Python 3.12, Improved Error Messages
- What's New In Python 3.12, Other Language Changes
- What's New In Python 3.12, New Features Related to Type Hints
- What's New In Python 3.12, Removed
- What's New In Python 3.12, Deprecated
- What's New In Python 3.12, Porting to Python 3.12
- What's New In Python 3.12, Notable changes in 3.12.4, 3.12.5 and 3.12.6
- What's New In Python 3.12, Notable changes in 3.12.16
- Changelog, Python 3.12 documentation, Python 3.12.16 final back to Python 3.12.0 final
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 XT07TD Edit this page History Report an error Markdown