Unlock Python 3.9‑3.12: New Built‑in Functions That Simplify Everyday Coding
This article walks through the most useful built‑in functions and modules introduced in Python 3.9 through 3.12—including str.removeprefix/removesuffix, math.dist, math.comb, zoneinfo, hashlib.blake2b, and tomllib—showing how they eliminate boiler‑plate, boost performance, and reduce external dependencies.
Introduction
Python 3.9‑3.12 added a series of "out‑of‑the‑box" utilities that target common pain points such as string trimming, geometric calculations, time‑zone handling, high‑performance hashing, and TOML configuration parsing. These additions let developers write clearer, faster code without pulling in third‑party packages.
1. String handling (Python 3.9+)
Previously, removing a known prefix or suffix required str.startswith / str.endswith checks combined with slicing or str.lstrip / str.rstrip, which could unintentionally strip characters. Python 3.9 introduced two precise methods:
str.removeprefix(prefix) str.removesuffix(suffix)They return the original string when the prefix/suffix does not match, ensuring safe, intent‑clear operations.
# Old way
if filename.startswith("2023_"):
clean_name = filename[5:]
print(clean_name) # report_final.pdf
# New way
clean_name = filename.removeprefix("2023_")
print(clean_name) # report_final.pdf
# Safe suffix removal
path = "project/utils.py"
print(path.removesuffix(".txt")) # project/utils.py
print(path.removesuffix(".py")) # project/utils2. Math & Statistics (Python 3.10+)
The math module now includes math.dist for Euclidean distance and math.comb / math.perm for combinatorial calculations, while statistics adds correlation, covariance, and linear_regression, reducing the need for heavy libraries like NumPy for lightweight analysis.
import math
point_a = (1, 2, 3)
point_b = (4, 5, 6)
print(f"Distance: {math.dist(point_a, point_b):.2f}") # 5.20
print(f"C(5,3) = {math.comb(5,3)}") # 10
print(f"A(5,3) = {math.perm(5,3)}") # 60
import statistics
x = [1,2,3,4,5]
y = [2,4,5,4,5]
print(f"Correlation: {statistics.correlation(x,y):.3f}")
print(f"Covariance: {statistics.covariance(x,y):.3f}")
slope, intercept = statistics.linear_regression(x, y)
print(f"y = {slope:.2f}x + {intercept:.2f}")3. Time & Zone handling (Python 3.9+)
Python 3.9 standardized time‑zone management by adding the zoneinfo module, which draws from the IANA database and replaces the older pytz workflow.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
beijing = datetime(2023,10,1,10,0, tzinfo=ZoneInfo("Asia/Shanghai"))
print(f"Beijing time: {beijing}")
ny = beijing.astimezone(ZoneInfo("America/New_York"))
print(f"New York time: {ny}")
utc_now = datetime.now(timezone.utc)
local_now = utc_now.astimezone()
print(f"Local time: {local_now}")4. Pure‑Python hashing (Python 3.11+)
The hashlib module now offers pure‑Python implementations of the BLAKE2 family ( blake2b and blake2s), useful when C extensions are unavailable.
import hashlib
data = b"Hello, Modern Python!"
hash_obj = hashlib.blake2b(data, digest_size=32)
print(f"BLAKE2b: {hash_obj.hexdigest()}")5. TOML parsing (Python 3.11+)
Python 3.11 introduced tomllib, a standard‑library TOML parser, allowing projects to read pyproject.toml or custom configuration files without external dependencies.
# config.toml
[database]
host = "localhost"
port = 5432
name = "mydb"
[server]
debug = true
allowed_hosts = ["127.0.0.1", "192.168.1.1"]
import tomllib
with open("config.toml", "rb") as f:
cfg = tomllib.load(f)
print(f"DB host: {cfg['database']['host']}")
print(f"Debug mode: {cfg['server']['debug']}")
print(f"Allowed hosts: {cfg['server']['allowed_hosts']}")Conclusion
From Python 3.9 to 3.12, each release adds features that make routine tasks simpler, code more robust, and performance better. The highlighted built‑ins are immediately applicable and represent a substantial productivity boost for everyday Python development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
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.
