Custom Format Codes in f-Strings: Python's __format__ Method

This article explains how format, str.format and f-strings delegate to the __format__ method, how a class can define format codes of its own and delegate numeric parts to the mini-language, and which pitfalls a careless implementation hides.

A bright green tree python with blue markings coiled around a bare branch against a soft green background.
Photo by Marius Masalar on Unsplash

An f-string such as f"{price:.2f}" contains two parts inside the braces: the expression that produces a value, and, after the colon, a format specification that says how the value must be written. The present article addresses the special method __format__, through which every object receives that specification and returns its own text, so that a class can define codes of its own in the same way that float defines .2f and datetime defines %Y. The protocol, its default behaviour, the delegation of numeric parts to the built-in mini-language and the errors that a careless implementation hides are examined in turn. Letting an object choose how it is written in an f-string, with a vocabulary as compact as that of the built-in types, is the secret weapon of the method __format__.

The Protocol Behind format, str.format and f-Strings

The built-in function format(value, spec) calls type(value).__format__(value, spec), and f-strings and the method str.format reach the same call, so a class that defines __format__ serves the three forms at once. The default implementation inherited from object accepts only an empty specification, in which case it returns str(value); since Python 3.4, any other specification raises TypeError. The conversions !s, !r and !a are applied before formatting, so they replace the object with a string whose own __format__ then handles the specification. The following example shows these rules with a class that defines only __str__, together with two built-in types that interpret specifications of their own.

import datetime


class Label:
    def __init__(self, text):
        self.text = text

    def __str__(self):
        return self.text


tag = Label("draft")
print(f"[{tag}]", format(tag, ""))  # Output: [draft] draft
try:
    f"{tag:>8}"
except TypeError as error:
    print(error)  # Output: unsupported format string passed to Label.__format__
print(f"[{tag!s:>8}]")  # Output: [   draft]

width = 10
print(f"[{3.14159:{width}.2f}]")  # Output: [      3.14]
print(f"{datetime.date(2026, 11, 30):%d %b %Y}")  # Output: 30 Nov 2026
print("{:,.2f}".format(1234567.891))  # Output: 1,234,567.89

The alignment >8 failed on the object itself and succeeded after !s, because the conversion handed a str to the formatting machinery. Nested fields such as {width} are evaluated before the call, so __format__ always receives the final text of the specification, here 10.2f. The date object interprets its specification as strftime codes, which shows that the meaning of the text after the colon belongs entirely to the type. The relation between __str__, __repr__ and the rest of the special methods is described in the article devoted to the data model.

Defining a Specification of One's Own

Many games let a player change the appearance of a piece of equipment without changing its statistics, so that the same item can be shown in several styles while remaining the same item. This means that __format__ alters only the presentation of an object: the value stays the same, and each specification selects one way of writing it. The analogy, however, stops at this point, because a chosen appearance persists on the item, whereas a format specification applies to a single expression and leaves no trace on the object. A well-designed __format__ separates the part of the specification that belongs to the class from the part that can be delegated to the built-in mini-language, and rejects what it does not understand. The following example formats a temperature in three units and delegates the numeric part to float.

class Temperature:
    UNITS = {
        "C": lambda c: c,
        "F": lambda c: c * 9 / 5 + 32,
        "K": lambda c: c + 273.15,
    }

    def __init__(self, celsius):
        self.celsius = celsius

    def __repr__(self):
        return f"Temperature({self.celsius!r})"

    def __format__(self, spec):
        unit = spec[-1:] if spec[-1:] in self.UNITS else "C"
        number_spec = spec[:-1] if spec[-1:] in self.UNITS else spec
        value = self.UNITS[unit](self.celsius)
        return f"{format(value, number_spec or '.1f')} {unit}"


t = Temperature(21.5)
print(f"{t}")       # Output: 21.5 C
print(f"{t:F}")     # Output: 70.7 F
print(f"{t:.2fK}")  # Output: 294.65 K
print(f"{t:>8.0fC}|")  # Output:       22 C|
print(f"{t!r}")     # Output: Temperature(21.5)
try:
    f"{t:X}"
except ValueError as error:
    print(error)  # Output: Unknown format code 'X' for object of type 'float'

The class reads only the last character as a unit and passes the rest to format on a float, so widths, alignment and precision behave exactly as for numbers, and an unknown code produces the error of the mini-language instead of a silent result. The conversion !r bypasses the method and shows the representation intended for developers. The same protocol is visible to str.format, so "{:F}".format(t) returns the same text as the f-string.

Pitfalls of format

The method receives an arbitrary string and must return a string, so its pitfalls come from specifications that are accepted without being understood and from results of the wrong type. Six pitfalls are distinguished, which are the following:

  1. Silent fallbacks. An implementation that returns a default text for any unknown specification turns a typing error, such as lod instead of loud, into a plausible output.
  2. Non-string results. Returning a number or None raises TypeError at the moment of formatting, far from the definition.
  3. Incomplete delegation. A numeric specification without a type, such as .0, uses the general format of float, so 294.65 with .0 becomes 3e+02.
  4. Forgotten empty specification. f"{obj}" calls __format__ with an empty string, which must produce a sensible default.
  5. Conversions that bypass the method. !s and !r format a string instead of the object, so a custom specification after them is interpreted by str.
  6. Cost. A __format__ written in Python adds a function call and whatever work it performs to every formatted value.

The first three pitfalls are reproduced in the following example.

class Name:
    def __init__(self, text):
        self.text = text

    def __format__(self, spec):
        if spec == "loud":
            return self.text.upper()
        return self.text


class Broken:
    def __format__(self, spec):
        return 42


user = Name("Arthur")
print(f"{user:loud} {user:lod}")  # Output: ARTHUR Arthur
try:
    f"{Broken()}"
except TypeError as error:
    print(error)  # Output: __format__ must return a str, not int
print(format(294.65, ".0"), format(294.65, ".0f"))  # Output: 3e+02 295

The misspelt lod produced the ordinary name without any warning, which is why an implementation should raise ValueError for specifications it does not recognize, as the delegation in the previous example does. On CPython 3.12, an f-string with a trivial __format__ that returns a constant took about 60 nanoseconds, the Temperature object of the previous section about 480, and a float with .1f about 130, so the cost lies in the work performed inside the method rather than in the protocol, and it matters only in loops that format millions of values.

Choosing How to Represent an Object

Consequently, __format__ suits values that are written in several standard styles, while a single canonical text belongs in __str__ and a diagnostic one in __repr__, as the following table summarizes.

Situation Recommended approach
One readable text for users __str__
An unambiguous text for developers __repr__
Several styles selected at the point of use __format__ with a small vocabulary
Numbers with units, currencies or measurements __format__ that delegates the numeric part to format
Width and alignment of an object without __format__ The conversion !s before the specification
Templates processed by other code, such as HTML or SQL t-strings of Python 3.14, whose format_spec the processing code interprets

Python 3.14 introduced template strings, whose interpolations keep the value, the conversion and the format specification separately; unlike f-strings, they do not apply the specification automatically, so the code that processes the template decides whether to call format.

Conclusion

It is concluded that format, str.format and f-strings all delegate to __format__, that the default implementation accepts only an empty specification, and that a custom implementation should return a string, delegate numeric parts to the mini-language and reject unknown codes. This magic remains a matter of presentation: it never changes the value, and conversions such as !r bypass it entirely. Building a small language of expressions from classes that each interpret one rule of a grammar, as the Interpreter pattern proposes, is the subject of a future article of this series.