New itertools, enum and stdlib helpers in Python 3.10-3.13

suggest change

Each Python release adds a few small helpers to the standard library. None of them is big enough to headline a release, but they replace code that people used to copy from Stack Overflow or the itertools recipes page. This article is a tour of the most useful ones:

Version Addition
3.10 itertools.pairwise(), zip(strict=True), parenthesized context managers, int.bit_count()
3.11 enum.StrEnum, enum.verify(), member()/nonmember(), iterable Flag values, contextlib.chdir()
3.12 itertools.batched(), Path.walk(), in with enum values
3.13 copy.replace(), batched(strict=True)

Examples were run with Python 3.13.15 on Windows. The map(strict=True) example was run with Python 3.14.4 on Ubuntu (WSL), and the "before" outputs with Python 3.10.

itertools.pairwise (3.10)

pairwise(iterable) yields overlapping pairs of consecutive items: (s0, s1), (s1, s2), (s2, s3), .... It's the standard way to compare each item with the next one:

from itertools import pairwise

print(list(pairwise("ABCD")))

temps = [12.0, 14.5, 13.0, 17.5, 21.0]
deltas = [b - a for a, b in pairwise(temps)]
print(deltas)

nums = [1, 3, 4, 9, 10]
print(all(a < b for a, b in pairwise(nums)))
print(list(pairwise([1])))
[('A', 'B'), ('B', 'C'), ('C', 'D')]
[2.5, -1.5, 4.5, 3.5]
True
[]

An iterable with fewer than two items gives no pairs. The all(a < b ...) line is a short way to check that a sequence is strictly increasing.

Before 3.10 you would write zip(seq, seq[1:]). That only works on sequences, and the slice makes a copy. pairwise works on any iterable, including generators that can be read only once:

from itertools import pairwise

route = ["Warsaw", "Berlin", "Paris", "Madrid"]
for start, end in pairwise(route):
    print(f"{start} -> {end}")

# works on any iterable, including generators that can be read only once
def readings():
    yield from (100, 104, 101, 110)

for prev, cur in pairwise(readings()):
    if cur - prev > 5:
        print("jump:", prev, "->", cur)
Warsaw -> Berlin
Berlin -> Paris
Paris -> Madrid
jump: 101 -> 110

itertools.batched (3.12)

batched(iterable, n) splits an iterable into tuples of length n. The last tuple can be shorter:

from itertools import batched

print(list(batched("ABCDEFG", 3)))

ids = range(1, 11)
for batch in batched(ids, 4):
    print("insert", batch)
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
insert (1, 2, 3, 4)
insert (5, 6, 7, 8)
insert (9, 10)

This is what you want for sending rows to a database or an API that limits the number of items per request. Before 3.12 the usual recipe was built on islice. It gives the same result:

from itertools import batched, islice

# the classic recipe from before 3.12
def chunks(iterable, n):
    it = iter(iterable)
    while chunk := tuple(islice(it, n)):
        yield chunk

print(list(chunks(range(7), 3)))
print(list(batched(range(7), 3)))
[(0, 1, 2), (3, 4, 5), (6,)]
[(0, 1, 2), (3, 4, 5), (6,)]

Python 3.13 added strict=True, which raises ValueError if the last batch is incomplete. Use it when the data must come in complete groups, for example when turning a flat list of keys and values into a dict:

from itertools import batched

pairs = "a1b2c3"
print(dict(batched(pairs, 2)))

try:
    list(batched("abcde", 2, strict=True))
except ValueError as e:
    print("ValueError:", e)
{'a': '1', 'b': '2', 'c': '3'}
ValueError: batched(): incomplete batch

The error is raised only when the last batch is reached, so all complete batches before it have already been produced. The Ranges article shows a range()-based way to chunk sequences, and the Itertools Module chapter covers the older functions.

zip(strict=True) (3.10)

zip() stops at the shortest iterable. If the inputs are supposed to have the same length, a mismatch is a bug that zip hides by silently dropping data. PEP 618 added strict=True, which raises ValueError instead:

names = ["ann", "bob", "cid"]
scores = [90, 85]

print(list(zip(names, scores)))

try:
    print(list(zip(names, scores, strict=True)))
except ValueError as e:
    print("ValueError:", e)

try:
    list(zip([1, 2], [3, 4, 5], strict=True))
except ValueError as e:
    print("ValueError:", e)
[('ann', 90), ('bob', 85)]
ValueError: zip() argument 2 is shorter than argument 1
ValueError: zip() argument 2 is longer than argument 1

The check happens lazily, when one iterable runs out. Pairs before that point have already been produced, so code in the loop body has already run:

def rows():
    print("reading row 1"); yield 1
    print("reading row 2"); yield 2
    print("reading row 3"); yield 3

labels = ["a", "b"]
try:
    for label, row in zip(labels, rows(), strict=True):
        print(label, row)
except ValueError as e:
    print("ValueError:", e)
reading row 1
a 1
reading row 2
b 2
reading row 3
ValueError: zip() argument 2 is longer than argument 1

If you need to validate before doing any work, compare len() first (for sequences) or build a list with list(zip(..., strict=True)).

Python 3.14 added the same option to map(). In 3.13 and earlier, map() takes no keyword arguments:

try:
    list(map(pow, [2, 3, 4], [5, 6], strict=True))
except ValueError as e:
    print("ValueError:", e)
$ python3.14 map314.py
ValueError: map() argument 2 is shorter than argument 1

$ python3.13 map314.py
TypeError: map() takes no keyword arguments

See also Mapping values of different iterables and, for the opposite behavior (padding the shorter input), Zipping two iterators until they are both exhausted.

Parenthesized context managers (3.10)

A with statement can take several context managers, as shown in Multiple context managers. When the line got too long, you had to use backslashes, nest the statements or use contextlib.ExitStack. Since 3.10 you can wrap the managers in parentheses and split them over several lines, with an optional trailing comma:

from pathlib import Path

Path("input.txt").write_text("one\ntwo\n")

with (
    open("input.txt") as src,
    open("output.txt", "w") as dst,
):
    for line in src:
        dst.write(line.upper())

print(Path("output.txt").read_text(), end="")
ONE
TWO

It works with any context managers, with or without as:

from contextlib import nullcontext, suppress
import threading

lock = threading.Lock()

with (
    lock,
    suppress(KeyError),
    nullcontext("value") as v,
):
    print(lock.locked(), v)
    {}["missing"]

print("after:", lock.locked())
True value
after: False

The managers are entered left to right and exited in reverse order, exactly like the single-line form. Here suppress(KeyError) swallows the exception and the lock is released afterwards.

The new PEG parser in 3.9 already accepted this syntax, but it became an official feature in 3.10. Code formatters like Black and Ruff use it when you target 3.10+.

contextlib.chdir (3.11)

contextlib.chdir(path) changes the current working directory for the duration of a with block and restores the previous one afterwards:

import os
from contextlib import chdir
from pathlib import Path

Path("build").mkdir(exist_ok=True)
print("before:", Path.cwd().name)

with chdir("build"):
    print("inside:", Path.cwd().name)
    Path("log.txt").write_text("built\n")

print("after: ", Path.cwd().name)
print(os.path.exists("build/log.txt"))
before: py20
inside: build
after:  py20
True

The old directory is restored even if the block raises:

from contextlib import chdir
from pathlib import Path

try:
    with chdir("build"):
        raise RuntimeError("compile failed")
except RuntimeError as e:
    print(e, "- cwd is back to", Path.cwd().name)
compile failed - cwd is back to py20

The working directory belongs to the whole process, so chdir() affects all threads and all asyncio tasks. Use it in scripts, tests and build tools, not in a web server or a library. When you only need to run a subprocess somewhere else, pass cwd= to subprocess.run() instead.

Path.walk (3.12)

pathlib had glob() and rglob(), but nothing like os.walk(), so recursive directory traversal with pruning meant leaving pathlib. Python 3.12 added Path.walk(). It yields (root, dirs, files) tuples like os.walk(), except that root is a Path:

from pathlib import Path

# create a small tree to walk
for f in ["proj/main.py", "proj/README.md", "proj/pkg/util.py",
          "proj/pkg/__pycache__/util.cpython-313.pyc", "proj/.git/HEAD"]:
    p = Path(f)
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text("x")

for root, dirs, files in Path("proj").walk():
    dirs.sort()
    print(root.as_posix(), sorted(dirs), sorted(files))
proj ['.git', 'pkg'] ['README.md', 'main.py']
proj/.git [] ['HEAD']
proj/pkg ['__pycache__'] ['util.py']
proj/pkg/__pycache__ [] ['util.cpython-313.pyc']

dirs and files are lists of names (strings), and their order depends on the file system. Sorting dirs in place makes the walk order deterministic. In the default top-down mode you can also remove entries from dirs to skip those subtrees, which rglob() can't do. Using the tree created above:

from pathlib import Path

SKIP = {".git", "__pycache__"}

py_files = []
for root, dirs, files in Path("proj").walk():
    dirs[:] = sorted(d for d in dirs if d not in SKIP)   # prune in place
    py_files += [root / f for f in files if f.endswith(".py")]

for p in sorted(py_files):
    print(p.as_posix())
proj/main.py
proj/pkg/util.py

Note dirs[:] = ...: assigning a new list to dirs would have no effect, because the walker keeps a reference to the original list.

With top_down=False each directory is yielded after its subdirectories, which is the order you need for deleting a tree:

import shutil
from pathlib import Path

shutil.copytree("proj", "proj_copy", dirs_exist_ok=True)

# bottom-up: files and subdirectories are removed before their parent
for root, dirs, files in Path("proj_copy").walk(top_down=False):
    for name in files:
        (root / name).unlink()
    for name in dirs:
        (root / name).rmdir()
Path("proj_copy").rmdir()
print(Path("proj_copy").exists())
False

(In real code shutil.rmtree() does this for you.) Other differences from os.walk(): the keyword arguments are top_down, on_error and follow_symlinks (default False), and symlinks to directories end up in files unless you follow them. Iterate files recursively shows the os.walk() version.

enum.StrEnum (3.11)

The book's Enum chapter covers the basics. Python 3.11 reworked the module and added several features.

StrEnum members are strings. They compare equal to their values, can be passed anywhere a str is expected, and str() and f-strings give the value. With auto(), the value is the lowercased member name:

from enum import StrEnum, auto

class Color(StrEnum):
    RED = auto()
    GREEN = auto()
    DARK_BLUE = "dark-blue"

print(Color.RED, Color.GREEN, Color.DARK_BLUE)
print(repr(Color.RED))
print(Color.RED == "red", isinstance(Color.RED, str))
print(f"color={Color.GREEN}", "-".join(Color))
print(Color("dark-blue"))
print(Color.RED.upper())
red green dark-blue
<Color.RED: 'red'>
True True
color=green red-green-dark-blue
dark-blue
RED

This is handy for values that end up in JSON, URLs, database columns or command line options.

Before 3.11 the usual spelling was class Color(str, Enum). It still works, but str() and format() of such a mixin give ClassName.MEMBER, so the value doesn't appear in f-strings. IntEnum changed in 3.11 too: its str() is now the number, as format() always was:

from enum import Enum, IntEnum

class OldColor(str, Enum):
    RED = "red"

class Level(IntEnum):
    LOW = 1
    HIGH = 2

print(f"{OldColor.RED}", str(OldColor.RED))
print(f"{Level.HIGH}", str(Level.HIGH), Level.HIGH + 1)
$ python3.13 enum2.py
OldColor.RED OldColor.RED
2 2 3

$ python3.10 enum2.py
red OldColor.RED
2 Level.HIGH 3

Note that the f-string output of the (str, Enum) mixin changed in 3.11, from red to OldColor.RED. If your code formats such enums, switch to StrEnum to get the value in every version.

enum.verify and other enum additions (3.11-3.12)

The @verify decorator checks constraints when the class is created. UNIQUE rejects aliases (two names with the same value), CONTINUOUS rejects gaps in integer values, and NAMED_FLAGS checks that combined Flag values only use named bits:

from enum import Enum, verify, UNIQUE, CONTINUOUS

try:
    @verify(UNIQUE)
    class Status(Enum):
        ACTIVE = 1
        ENABLED = 1      # alias by accident
        DISABLED = 2
except ValueError as e:
    print("ValueError:", e)

try:
    @verify(CONTINUOUS)
    class Weekday(Enum):
        MON = 1
        TUE = 2
        THU = 4
except ValueError as e:
    print("ValueError:", e)
ValueError: aliases found in <enum 'Status'>: ENABLED -> ACTIVE
ValueError: invalid enum 'Weekday': missing values 3

@verify(UNIQUE) does the same job as the older @unique decorator. You can pass several checks: @verify(UNIQUE, CONTINUOUS).

Flag values became iterable in 3.11. Iterating gives the individual members, len() counts them, and aliases (like RW below) are skipped when you iterate over the class:

from enum import Flag, auto

class Perm(Flag):
    R = auto()
    W = auto()
    X = auto()
    RW = R | W

p = Perm.R | Perm.X
print(p)
print(list(p), len(p))
print(list(Perm))
print(Perm.RW in Perm.R | Perm.W | Perm.X)
print(~Perm.R)
Perm.R|X
[<Perm.R: 1>, <Perm.X: 4>] 2
[<Perm.R: 1>, <Perm.W: 2>, <Perm.X: 4>]
True
Perm.W|X

In 3.10, list(p) raises TypeError: 'Perm' object is not iterable, and ~Perm.R lists the bits in reverse order (Perm.X|W).

member() and nonmember() override the rules for what becomes a member. Normally every plain attribute is a member and every function is a method:

from enum import Enum, member, nonmember

class Planet(Enum):
    MERCURY = 1
    EARTH = 3
    G = nonmember(6.674e-11)              # plain class attribute

    @member
    def describe(self):                   # would normally be a method
        return "a function value"

print([m.name for m in Planet])
print(Planet.G)
['MERCURY', 'EARTH', 'describe']
6.674e-11

Finally, since 3.12 you can test a plain value with in. In 3.11 and earlier, "small" in Size raises TypeError because the left side isn't a member:

from enum import Enum

class Size(Enum):
    S = "small"
    M = "medium"

print("small" in Size, "huge" in Size, Size.S in Size)
True False True

This replaces the try: Size(value) except ValueError: dance when you only need a yes/no answer.

copy.replace (3.13)

copy.replace(obj, **changes) creates a copy of obj with some attributes changed. It's a single function for all the types that had their own replace() or _replace() method:

import copy
from collections import namedtuple
from dataclasses import dataclass
from datetime import date

Point = namedtuple("Point", "x y")
print(copy.replace(Point(1, 2), y=20))

print(copy.replace(date(2026, 10, 18), day=1))

@dataclass(frozen=True)
class Config:
    host: str
    port: int = 80

print(copy.replace(Config("example.com"), port=443))
Point(x=1, y=20)
2026-10-01
Config(host='example.com', port=443)

It works with named tuples, dataclasses, datetime, date, time, inspect.Signature, types.SimpleNamespace and code objects. Your own classes can support it by defining __replace__:

import copy

class Money:
    def __init__(self, amount, currency):
        self.amount, self.currency = amount, currency

    def __replace__(self, **changes):
        return Money(changes.get("amount", self.amount),
                     changes.get("currency", self.currency))

    def __repr__(self):
        return f"Money({self.amount}, {self.currency!r})"

print(copy.replace(Money(10, "EUR"), amount=25))

try:
    copy.replace([1, 2], x=1)
except TypeError as e:
    print("TypeError:", e)
Money(25, 'EUR')
TypeError: replace() does not support list objects

Built-in containers like list, dict and tuple don't support it, since they have no named fields. The Dataclasses article covers dataclasses.replace() and copy.replace() for frozen dataclasses in more detail.

A few more small additions

Some other one-liners worth knowing:

import math, operator, statistics

print((0b1011_0110).bit_count())              # 3.10
print(math.cbrt(27), math.exp2(10))           # 3.11
print(operator.call(max, 3, 9, 4))            # 3.11
print(math.sumprod([1, 2, 3], [4, 5, 6]))     # 3.12
print(statistics.fmean([1, 2, 3], weights=[3, 1, 1]))  # 3.11
print(math.fma(2.0, 3.0, 1.0))                # 3.13
5
3.0 1024.0
9
32
1.6
7.0

Summary

Task Code Since
consecutive pairs itertools.pairwise(it) 3.10
fixed-size chunks itertools.batched(it, n) 3.12
chunks that must be complete batched(it, n, strict=True) 3.13
zip that rejects length mismatch zip(a, b, strict=True) 3.10
same for map map(f, a, b, strict=True) 3.14
long with statements with (a as x, b as y,): 3.10
temporary working directory with contextlib.chdir(path): 3.11
recursive walk with pruning Path.walk() 3.12
string-valued enum class C(StrEnum) 3.11
check enum values at definition @verify(UNIQUE, CONTINUOUS) 3.11
members of a flag value list(flag), len(flag) 3.11
is a value valid for an enum value in MyEnum 3.12
copy with changed fields copy.replace(obj, **changes) 3.13

Things to remember:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents