ZetCode

Python __format__ Method

Last modified November 17, 2026 Python 3.15

The format() built-in and f-strings call __format__ with a format specification string. A custom type can interpret that string itself, delegate it to a built-in type, or define a small formatting language. This article shows the dispatch, the specification string, delegation, composite formatting, and the return-type rule.

How formatting calls __format__

format(obj, spec) and f"{obj:spec}" both call type(obj).__format__(obj, spec). When no specification is given, the hook receives the empty string. It must return a str.

basic_format.py
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __format__(self, format_spec):
        if format_spec == "f":
            return f"{self.celsius * 9 / 5 + 32:.2f}F"
        if format_spec == "k":
            return f"{self.celsius + 273.15:.2f}K"
        return f"{self.celsius:.2f}C"


t = Temperature(25)
print(f"default: {t}")
print(f"fahrenheit: {t:f}")
print(f"kelvin: {t:k}")
print(format(t, "f"))

The temperature class treats f and k as its own specifiers and uses the empty string for the default. Calling format(t, "f") gives the same result as the f-string, confirming that both routes reach the hook.

$ python basic_format.py
default: 25.00C
fahrenheit: 77.00F
kelvin: 298.15K
77.00F

The specification is just a string

Python does not parse the specification for custom objects; the hook gets exactly the text after the colon. What that text means is entirely up to the class.

echo_spec.py
class Echo:
    def __format__(self, format_spec):
        return f"spec={format_spec!r}"


obj = Echo()
print(f"{obj}")
print(f"{obj:>12}")
print(format(obj, "hello"))

An omitted specification arrives as an empty string, >12 is received unchanged, and an arbitrary word is passed through as well. Built-in types interpret the format mini-language; a custom type may reuse it or ignore it.

$ python echo_spec.py
spec=''
spec='>12'
spec='hello'

Delegating to a built-in type

The easiest way to support the standard mini-language is to convert the value to a built-in numeric type and pass the specification on to format().

fixedpoint.py
class FixedPoint:
    def __init__(self, value, scale=100):
        self.value = value
        self.scale = scale

    def __format__(self, format_spec):
        number = self.value / self.scale
        if not format_spec:
            return str(number)
        return format(number, format_spec)


num = FixedPoint(31415)
print(f"{num}")
print(f"{num:.2f}")
print(f"{num:10.2f}")
print(f"{num:>10.2f}")

The stored integer is scaled to a float, then the float's own __format__ handles precision, width, and alignment. The empty specification is handled separately so the default is the plain number.

$ python fixedpoint.py
314.15
314.15
    314.15
    314.15

A small custom language

A class can give the specification its own meaning, using a separator to carry several options. The example splits the string into a style and an optional unit.

person.py
class Person:
    def __init__(self, name, age, height):
        self.name = name
        self.age = age
        self.height = height

    def __format__(self, format_spec):
        if not format_spec:
            return f"{self.name} (age {self.age}, {self.height} cm)"
        style, _, unit = format_spec.partition(":")
        if style == "short":
            return self.name
        if style == "long":
            if unit == "imperial":
                return f"{self.name}, {self.age}, {self.height / 2.54:.1f} in"
            return f"{self.name}, {self.age}, {self.height} cm"
        return f"unknown format: {format_spec!r}"


p = Person("Alice", 30, 170)
print(f"{p}")
print(f"{p:short}")
print(f"{p:long}")
print(f"{p:long:imperial}")
print(f"{p:weird}")

An empty specification gives a full description, short gives just the name, and long:imperial adds a unit choice. An unknown style returns a message instead of raising, which is a deliberate choice; a stricter class would raise ValueError.

$ python person.py
Alice (age 30, 170 cm)
Alice
Alice, 30, 170 cm
Alice, 30, 66.9 in
unknown format: 'weird'

Formatting composite objects

An outer object can forward its specification to the objects it contains, keeping a whole report consistent with one format string.

report.py
class Item:
    def __init__(self, name, price, qty):
        self.name = name
        self.price = price
        self.qty = qty

    def __format__(self, format_spec):
        if format_spec == "csv":
            return f"{self.name},{self.price:.2f},{self.qty}"
        return f"{self.name:<10} ${self.price:>6.2f} x{self.qty:03}"


class Report:
    def __init__(self, items):
        self.items = items

    def __format__(self, format_spec):
        lines = [format(item, format_spec) for item in self.items]
        if format_spec == "csv":
            return "name,price,qty\n" + "\n".join(lines)
        return "ITEMS\n" + "\n".join(lines)


items = [Item("Widget", 12.99, 42), Item("Gadget", 7.5, 13)]
report = Report(items)
print(f"{report}")
print(f"{report:csv}")

The report passes its specification to each item, so {report:csv} produces comma-separated rows from the same objects that render as a table by default. Both classes implement their own __format__.

$ python report.py
ITEMS
Widget     $ 12.99 x042
Gadget     $  7.50 x013
name,price,qty
Widget,12.99,42
Gadget,7.50,13

The return value must be a string

Python requires __format__ to return a str. The caller does not convert the result, so returning any other type raises TypeError.

bad_format.py
class Bad:
    def __format__(self, format_spec):
        return 42


try:
    format(Bad())
except TypeError as e:
    print(type(e).__name__, e)

The error names the method and the offending type. Convert numbers or other objects with str() or an f-string before returning them.

$ python bad_format.py
TypeError Bad.__format__() must return a str, not int

Best practices

Formatting is a presentation concern, so keep it predictable:

Source

object.__format__ - Python documentation

Format Specification Mini-Language - Python documentation

format() - Python documentation

In this article we have implemented the __format__ method. We have covered the format() dispatch, the specification string, delegation, custom languages, composite objects, and the return type. For related topics, see Python format() function, Python f-string, and Python __str__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.