Key New Features and Improvements in Python 3.12
Python 3.12 introduces enhanced error messages, expanded f‑string capabilities, inline collection optimizations, new buffer protocol support, refined type‑annotation syntax, additional language tweaks, and performance‑focused garbage‑collector changes, providing developers with clearer diagnostics and more expressive, efficient code constructs.
Python 3.12 was officially released, bringing a range of language‑level enhancements and performance improvements.
Improved error messages
Standard‑library modules now provide more informative NameError messages, suggesting possible fixes such as missing imports or undefined variables. Example:
<code>>> sys.version_info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined. Did you forget to import 'sys'?</code>Similar enhancements apply to ImportError and SyntaxError , offering concrete suggestions.
<code>>> from collections import chainmap
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'chainmap' from 'collections'. Did you mean: 'ChainMap'?</code>New features
PEP 701 – f‑string semantic formatting
f‑strings now accept any valid Python expression, including backslashes, Unicode escapes, multiline expressions, comments, and repeated quote styles. This also removes the previous four‑level nesting limit.
<code>>> songs = ['Take me back to Eden', 'Alkaline', 'Ascensionism']
>>> f"This is the playlist: {', '.join(songs)}"
'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'</code>Nested f‑strings can now be arbitrarily deep:
<code>>> f"""{f'''{f'{f"{1+1}"}'}'''}"""
'2'</code>PEP 709 – Inline collection behavior
The interpreter now treats dictionaries, lists, and sets as inline objects, allowing the VM to optimise their creation and potentially double execution speed; iterators are excluded.
PEP 688 – Buffer protocol exposure
Classes implementing __buffer__() can be used as buffer objects, and the new abstract base class collections.abc.Buffer together with inspect.BufferFlags standardises buffer usage.
Type‑annotation related updates
PEP 692 – TypedDict for **kwargs
Provides precise typing for **kwargs using TypedDict and Unpack :
<code>from typing import TypedDict, Unpack
class Movie(TypedDict):
name: str
year: int
def foo(**kwargs: Unpack[Movie]): ...
</code>PEP 698 – typing.override decorator
Ensures a method correctly overrides a parent method, similar to Java’s @Override.
<code>from typing import override
class Base:
def get_color(self) -> str:
return "blue"
class GoodChild(Base):
@override
def get_color(self) -> str:
return "yellow"
class BadChild(Base):
@override
def get_colour(self) -> str: # type‑checker error
return "red"
</code>PEP 695 – Parameter‑type syntax
Introduces concise generic syntax and new type alias declarations, supporting TypeVarTuple , ParamSpec , and bounded type variables.
<code>def max[T](args: Iterable[T]) -> T: ...
class list[T]:
def __getitem__(self, index: int, /) -> T: ...
def append(self, element: T) -> None: ...
type Point = tuple[float, float]
type Point[T] = tuple[T, T]
type IntFunc[**P] = Callable[P, int] # ParamSpec
type LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple
</code>Other language changes (partial)
New environment variable PYTHONPERFSUPPORT and -X perf flag for Linux perf profiling.
Hashable MappingProxyType when underlying dict is hashable.
Parser can now handle empty bytes.
Garbage collector runs only at bytecode pause points and during signal checks, reducing interruptions during C‑extension execution.
Walrus operator usable inside comprehensions.
slice objects are now hashable.
sum() uses a more accurate algorithm.
Conclusion
The highlighted changes show the Python Steering Council focusing on richer type‑annotation support and more efficient garbage‑collection, addressing long‑standing concerns about Python’s dynamic typing and performance.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.