Improvement in Modules
Python 3.12, along with the addition of completely new features also introduced new functionalities and improved the performance of the existing modules. Let us see each module one by one.
The new array module has a feature of subscription, which is included in array.array class. It provides more flexibility and an easier access to the element while working with Python arrays and making it a generic type.
import array
arr = array.array('i', [1, 2, 3, 4, 5])
print(arr[0])
Output:
1
Asyncio
Python 3.12 brings a number of improvements to asyncio module. The framework avoids unnecessary copying when writing to sockets improves the performance by utilizing sendmsg() if the platform supports it. The addition of asyncio.eager_task_factory() and asyncio.create_eager_task_factory() functions for opting into eager task execution, also results in faster performance. The child process monitoring is also improved by default usage of asyncio.PidfdChildWatcher on Linux if os.pidfd_open() is available.
Addition of enums calendar.Month and calendar.Day in calendar module, providing standardized representations for months of the year and days of the week. These enums enhance code readability and maintainability when working with calendar-related functionalities.
In CSV module, addition of csv.QUOTE_NOTNULL and csv.QUOTE_STRINGS flags for finer control over handling None and empty strings by csv.writer objects.
import csv
data = [['Alice', None], ['Bob', ''], ['Charlie', 'Developer']]
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NOTNULL)
writer.writerows(data)
Itertools
A new function in itertools module, itertools.batched() is added for collecting into even-sized tuples where the last batch may be shorter than the rest. This is useful for batch processing of data.
import itertools
data = [1, 2, 3, 4, 5, 6]
batched_data = list(itertools.batched(data, 3))
print(batched_data)
Output:
[(1, 2, 3), (4, 5, 6)]
Math
Addition of math.sumprod() in the math module for computing a sum of products and extension of math.nextafter() to include a steps argument for moving up or down multiple steps at a time.
In os module, the improvement in the accuracy and performance of os.stat() and os.lstat() on Windows, providing more reliable file system information. Introduction of os.PIDFD_NONBLOCK to open a file descriptor for a process in non-blocking mode.
Introduction of new functions like os.listdrives(), os.listvolumes(), and os.listmounts() on Windows for enumerating drives, volumes, and mount points.
import os
print(os.listdrives())
Pathlib
The pathlib.Path.walk() is added for walking directory trees, similar to os.walk(). The pathlib.Path.glob(), pathlib.Path.rglob(), and pathlib.PurePath.match() now accept a case_sensitive parameter for precise matching control.
from pathlib import Path
for file in Path('/path/to/dir').rglob('*.txt', case_sensitive=True):
print(file)
Random
The random.binomialvariate(n, p) is added to the Python random module, which returns the number of successes for n independent trials with the probability of success in each trial being p.
Shutil
Python 3.12 version has improved a lot of shutil module’s functions. The shutil.make_archive() now passes the root_dir argument to custom archives to improve the flexibility. The shutil.rmtree() accepts a new argument onexc for error handling, replacing the deprecated onerror. While shutil.which() on Windows now consults the PATHEXT environment variable for executable matches.
import shutil
shutil.make_archive('archive', 'zip', root_dir='/path/to/dir')
Sqlite3
There is an addition command-line interface for SQLite. Introduction sqlite3.Connection.autocommit attribute and autocommit parameter in sqlite3.connect() for transaction handling control.
import sqlite3
conn = sqlite3.connect('example.db', autocommit=True)
Statistics
The statistics.correlation() has been extended to include a ranked method for computing the Spearman correlation of ranked data.
import statistics
data1 = [1, 2, 3, 4, 5]
data2 = [5, 4, 3, 2, 1]
correlation = statistics.correlation(data1, data2)
print(correlation)
Output:
Output: -1.0
Tempfile
The tempfile.NamedTemporaryFile() function now supports a new optional parameter delete_on_close.
import tempfile
with tempfile.NamedTemporaryFile(delete_on_close=True) as temp_file:
temp_file.write(b"Temporary data")
Threading
Two new functions – threading.settrace_all_threads() and threading.setprofile_all_threads() are added to set tracing and profiling functions in all running threads.
import threading
def trace(frame, event, arg):
print(f"Trace event: {event} in thread {threading.get_ident()}")
threading.settrace_all_threads(trace)
The tkinter.Canvas.coords() now accepts coordinates grouped in pairs for increased readability and ease of use.
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root)
canvas.create_rectangle((10, 10), (50, 50))
canvas.pack()
root.mainloop()
Tokenize
Changes from PEP 701 are included, providing more flexible f-string expression components.
import tokenize
source = 'f"This is {some_var}."'
tokens = tokenize.tokenize(iter(source.splitlines()))
for token in tokens:
print(token)
Types
The types.get_original_bases() is added for further introspection of user-defined generic types when subclassed.
import types
class MyList(list):
pass
print(types.get_original_bases(MyList))
Output:
(<class 'list'>,)
Typing
The isinstance() checks against runtime-checkable protocols now utilize inspect.getattr_static() for attribute lookup, preventing unexpected evaluation of descriptors and __getattr__() methods during protocol checks. This ensures more accurate and efficient type checking against protocols.
Members of runtime-checkable protocols are now considered “frozen” at runtime, improving performance by speeding up isinstance() checks against protocols with a few members.
Unicodedata
Updated Unicode database to version 15.0.0, providing the latest Unicode character information.
import unicodedata
print(unicodedata.name('A'))
Output:
LATIN CAPITAL LETTER A
A –durations command line option is added to display the N slowest test cases.
python3 -m unittest --durations=3 tests.test_module
Added a command-line interface for generating UUIDs.
python3 -m uuid
Python 3.12 – What’s New and How to Download?
Python releases a new version almost every year. The latest version, that is, Python 3.12 was released on 2 October, 2023. This version introduced many new features and improvements. In this article, we will see some of the newly added features to Python 3.12.
Table of Content
- Download and Install Python
- Improved Error Messages in Python
- More Flexibility in Python F-String
- Type Parameter Syntax
- Improvement in Modules
- Syntactic Formalization of f-strings
- Per-Interpreter GIL
- Low Impact Monitoring for CPython
- Conclusion