What's New In Python 3.13
Python 3.13 introduces several new features and improvements aimed at enhancing performance, developer experience, and security. Here’s a big overview of some of the most notable updates in Python 3.13, along with code examples where applicable.
1. Syntax & Language Features
1.1 except*
for Grouped Exceptions
Python 3.13 introduces except*
to handle multiple exceptions raised in an async
context, such as those that come from asyncio tasks. This allows you to catch and handle specific exceptions individually even when they are raised concurrently.
async def func():
raise ValueError("error 1")
async def another_func():
raise TypeError("error 2")
async def main():
try:
await asyncio.gather(func(), another_func())
except* ValueError as ex_val:
print(f"Caught a ValueError: {ex_val}")
except* TypeError as ex_type:
print(f"Caught a TypeError: {ex_type}")
asyncio.run(main())
This helps with improved exception handling, especially in asynchronous programming.
2. Performance Improvements
Python 3.13 continues to optimize the performance of the interpreter. Key areas of improvement include:
- Bytecode Optimizations: Better utilization of faster opcodes and optimizations in the instruction set.
- Faster Attribute Access: Accessing object attributes is now faster due to internal optimizations.
3. New Standard Library Modules & Features
3.1 tomllib
(Previously added but expanded support)
The tomllib
module allows parsing TOML (Tom's Obvious, Minimal Language) files natively in Python without third-party packages. This is now expanded with better functionality in Python 3.13.
import tomllib
toml_str = """
[section]
key = "value"
"""
data = tomllib.loads(toml_str)
print(data) # Output: {'section': {'key': 'value'}}
3.2 Expanded dataclasses
The dataclasses
module now supports more advanced features like customization of how fields are compared, serialized, or excluded.
from dataclasses import dataclass, field
@dataclass(order=True)
class Person:
name: str
age: int = field(compare=False)
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
# Comparison is now based only on the `name`
print(p1 > p2) # Output: False
4. Enhanced typing
Capabilities
Python 3.13 enhances the typing
module with better support for static type checkers and more intuitive typing features.
Self
type hint: You can now useSelf
in method signatures to indicate that the method returns an instance of the same class, improving clarity in class hierarchies.
from typing import Self
class Animal:
def set_name(self, name: str) -> Self:
self.name = name
return self
dog = Animal().set_name("Fido")
- Literal String Interpolation (PEP 701): You can now use literal string interpolation directly in string literals, similar to f-strings, but with a clearer syntax.
name = "World"
message = `Hello, {name}!` # new syntax for f-strings
print(message) # Output: Hello, World!
5. Pattern Matching Enhancements
The pattern matching feature, introduced in Python 3.10, gets several refinements in Python 3.13. The new improvements allow for more concise and efficient matching, particularly when dealing with nested data structures or catching specific exceptions.
match data:
case {"type": "person", "name": name, "age": age} if age > 18:
print(f"Adult: {name}")
case {"type": "person", "name": name}:
print(f"Minor: {name}")
case _:
print("Unknown type")
6. Async IO Enhancements
Async IO sees further enhancements in Python 3.13, including improvements in asyncio
performance, and better error handling in async contexts.
import asyncio
async def fetch_data():
await asyncio.sleep(1)
return {"data": "value"}
async def main():
task = asyncio.create_task(fetch_data())
try:
result = await task
print(result)
except Exception as e:
print(f"Error: {e}")
asyncio.run(main())
7. Deprecations and Removals
Python 3.13 removes or deprecates certain features as part of its lifecycle:
- Deprecated
distutils
:distutils
has been deprecated and removed, withsetuptools
taking over most of its functionality. - Removed old
async
andawait
syntax: Support for the legacy usage ofasync
andawait
in contexts where they aren't required has been removed.
8. Buffer Protocol Improvements
Python 3.13 introduces a refined buffer protocol that allows working with binary data more efficiently, especially in I/O and memory management contexts.
# Example of handling buffers in a binary file
with open("data.bin", "rb") as f:
buffer = memoryview(f.read())
print(buffer[:5]) # Prints first five bytes
9. Security Improvements
Python 3.13 continues to improve security, with updates like:
- Secure Hashing Algorithms: Updates to default hashing algorithms in the
hashlib
module to better support modern cryptographic standards. - PEP 681 - Marking APIs as Private: A new mechanism allows developers to mark certain parts of the public API as private or internal, discouraging their direct usage and protecting sensitive functionality.