Overview Python 3.12 introduces significant refinements to the language's internal architecture and developer experience. This release prioritizes smarter debugging tools, memory efficiency, and a drastic simplification of type-related syntax. By streamlining how the interpreter handles comprehensions and generic types, this version reduces boilerplate while boosting execution speed. Prerequisites To get the most out of this guide, you should have a solid grasp of Python 3.11 fundamentals, including list comprehensions, basic type hinting, and object-oriented programming. Familiarity with the Global Interpreter Lock (GIL) will help you understand the experimental threading improvements. Key Libraries & Tools - pathlib: Updated with a new `walk()` method for easier directory navigation. - typing: Updated to support new syntax for generics and the `@override` decorator. - asyncio: Now the primary package for concurrent operations as older modules are retired. Code Walkthrough Simplified Generics Previously, defining generic classes required manual `TypeVar` declarations. PEP 695 introduces a cleaner, inline syntax. ```python The Old Way from typing import TypeVar, Generic T = TypeVar("T", bound=str) class Container(Generic[T]): ... The Python 3.12 Way class Container[T: str]: def get_data() -> T: ... ``` This new syntax eliminates the need for separate variable assignments and makes generic definitions look more like other modern languages. The Override Decorator To prevent accidental errors when subclassing, use the `@override` decorator to ensure you are actually modifying a base class method. ```python from typing import override class Base: def get_color(self): return "blue" class Child(Base): @override def get_color(self): # Type checkers will error if this is misspelled return "red" ``` Syntax Notes F-strings are now fully formalized using the new PEG parser. You can now nest double quotes within f-strings without switching to single quotes, allowing for complex expressions like `f"{strings["key"]}"` directly within the template. Practical Examples Use the new `pathlib.Path.walk()` to recursively process files without relying on the older `os.walk` interface. This keeps your code consistent within the pathlib ecosystem. Additionally, utilize Immortal Objects for global constants; because their reference counts never change, they avoid cache invalidation in multi-threaded environments. Tips & Gotchas Watch out for removed modules! Python 3.12 officially deletes `distutils`, `asyncore`, and `asynchat`. If your project still relies on these, migrate to setuptools or asyncio immediately. Also, note that while per-interpreter GIL support exists in the C-API, you won't see the full Python-level interface until 3.13.
PEP 695
Concepts
- Sep 29, 2023