archive2019

f-strings, dataclasses and the walrus operator: Python 3.6 to 3.8 in my scripts

Three Python releases, three features that changed how my scripts look. How each works, the traps I hit, and the places where I still do not use them.

4 min read#dev#python

Three Python releases in a row each brought one feature that changed how my scripts look: f-strings in 3.6 (December 2016), dataclasses in 3.7 (June 2018), and assignment expressions in 3.8, which was released on 14 October 2019. With 3.8 out, my rules for all three fit on one page.

f-strings (3.6)

Formatted string literals (PEP 498) put the expression where the value goes:

room, temp = "kitchen", 21.456

print(f"{room}: {temp:.1f} C")              # kitchen: 21.5 C
print(f"{room.upper()}: {temp * 9 / 5 + 32:.1f} F")
f"{42:5d}"      # '   42'
f"{0.25:.0%}"   # '25%'
f"{1234567:,}"  # '1,234,567'

After the : comes the same format spec as in str.format(). !r uses repr(), which I like in debug output because it shows quotes and trailing spaces: f"user={name!r}" prints user='pi '.

With % or .format() and many arguments, I had to count positions to see which value goes where. With an f-string the value sits where it is used.

I still do not use them in three places:

  • Logging calls. log.debug("reading from %s: %s", sensor_id, value) builds the message only when the level is enabled. An f-string is always built.
  • SQL. Never format values into SQL. Use parameters: cur.execute("SELECT * FROM readings WHERE room = ?", (room,)).
  • Templates from a file. An f-string is evaluated where it is written, so it cannot be a template stored in a config file. str.format() or string.Template can.

Inside the braces you cannot reuse the outer quote type (f"{d['key']}" works, f"{d["key"]}" does not), and backslashes are not allowed. A literal brace is doubled: f"{{literal}}".

Dataclasses (3.7)

dataclasses (PEP 557) writes __init__, __repr__ and __eq__ from annotated class attributes. My scripts have many small data objects, like a sensor reading, a device config or a message to publish. Before, I used dicts (typos are silent), namedtuple (awkward defaults) or full classes with a lot of boilerplate.

from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
from typing import List

@dataclass(frozen=True)
class Reading:
    sensor_id: str
    temp_c: float
    hum: float
    ts: datetime = field(default_factory=lambda: datetime.now(timezone.utc))

@dataclass
class DeviceConfig:
    name: str
    interval_s: int = 30
    topics: List[str] = field(default_factory=list)

    def __post_init__(self):
        if self.interval_s < 1:
            raise ValueError("interval_s must be >= 1")

A reading should not change after it is created, so it is frozen=True. Assigning to a field then raises an error, and the object is hashable. The generated __init__ does not check types; the annotations are only hints. Real checks go into __post_init__.

Two errors from my first hour with them:

  • A list as a default (topics: List[str] = []) raises ValueError when the class is defined, because all instances would share one list. Use field(default_factory=list).
  • A field without a default after a field with one raises TypeError. With inheritance this gets worse, so I keep data classes flat.

asdict() turns an object into a dict. A datetime stays a datetime, so json.dumps(asdict(r), default=str) needs the converter. The way back is DeviceConfig(**json.loads(text)), which fails on unknown keys. For config files that is what I want. Dataclasses do not convert "30" to 30, so for messy input they are not a validation tool.

Assignment expressions (3.8)

:= (PEP 572) assigns a value inside an expression. I found two places where it makes code shorter without making it harder to read. Reading in a loop:

while line := ser.readline():
    handle(line)

And a regex match that is tested and then used:

if m := re.match(r"temp=([\d.]+)'C", output):
    temp = float(m.group(1))

When you compare the value, put the assignment in parentheses: if (n := len(data)) > 10:. Without them, n gets the result of the comparison, a bool. I made exactly this mistake on my first try. I do not use := in list comprehensions or long conditions, where it saves a line and costs the reader time.

Two smaller 3.8 additions I use: f"{temp=}" prints temp=21.5, the expression and its value, which is handy for debugging. And functools.cached_property computes a value once per instance. Positional-only parameters (def c_to_f(celsius, /)) are mainly for library authors, who can then rename a parameter without breaking callers.

Which Python runs where

New syntax is the problem, not new functions. An f-string in a file that runs on Python 3.5 is a syntax error, so the whole file fails to load, not only that line. Raspbian Buster ships Python 3.7 and Ubuntu 18.04 ships 3.6. So 3.8 syntax goes only into tools that run on my laptop or in Docker (python:3.8-slim), and the scripts on the Pis wait for the distribution. Before moving a project, check that its packages with C extensions, numpy or OpenCV for example, already have wheels for the new version.