__format__

__format__(self, format_spec)
Returns: str · Updated March 28, 2026 · Dunder Methods
dunder formatting string

What __format__ Does

__format__ controls how an object looks when it appears inside an f-string or gets passed to the built-in format() function. Every time Python evaluates an expression like f"{obj:spec}", it calls obj.__format__("spec") behind the scenes.

Without __format__ defined, Python falls back to __str__, and if that’s also absent, to __repr__.

Signature

def __format__(self, format_spec: str) -> str:
    ...
  • self — the object being formatted
  • format_spec — the format specification string (everything after the : in an f-string)
  • Return type is always str

The critical detail: format_spec is the full spec string, not just the type character. When you write f"{3.14159:.2f}", your __format__ receives ".2f", not "f".

How __format__ Differs from __str__ and __repr__

MethodArgumentsCalled byPurpose
__repr__selfrepr(obj)Developer/debugging output
__str__selfstr(obj), print(obj)Human-readable output
__format__self, format_specformat(obj, spec), f"{obj:spec}"Formatted user output

__str__ takes no arguments. You can’t pass a format specification to it. __format__ exists precisely because sometimes you need to control how an object renders in different contexts — the same object might display as "5.23km" in one place and "523400.0cm" in another.

The Fallback Chain

Python’s formatting pipeline follows this order:

f"{obj:spec}"  or  format(obj, spec)
    → calls __format__(obj, spec)
        → if __format__ is not defined:
            → calls __str__(obj)
                → if __str__ is not defined:
                    → calls __repr__(obj)

This means any class that defines __format__ is fully responsible for producing the string output. You can’t rely on the fallback to save you if you return the wrong type.

Format Specification Mini-Language

When __format__ receives a standard format spec, Python’s built-in formatting machinery can interpret it. The mini-language covers alignment, numeric flags, type characters, width, and precision.

Alignment

SpecMeaning
>Align right
<Align left
^Center
=Pad after sign (for numbers)
>>> f"{'hello':>10}"
'     hello'
>>> f"{'hello':<10}"
'hello     '
>>> f"{'hello':^10}"
'  hello   '

Numeric Flags

SpecMeaning
+Always show sign
-Negative sign only (default)
Space for positive, - for negative
#Alternate form (e.g., 0x prefix for hex)
0Zero-padding
>>> f"{42:+}"
'+42'
>>> f"{-42:+.2f}"
'-42.00'
>>> f"{42:#x}"
'0x2a'

Type Characters

SpecMeaning
fFixed-point (decimal)
e / EScientific notation
%Percentage (multiplies by 100)
,Thousands separator
bBinary
oOctal
x / XHexadecimal
dDecimal (integer)
g / GGeneral (auto-switches)

Width and Precision

>>> f"{3.14159:10.2f}"
'      3.14'
>>> f"{1234567:,}"
'1,234,567'
>>> f"{0.456:.1%}"
'45.6%'

Practical Example: Distance with Custom Format Specs

A common use case for __format__ is adding domain-specific format specifications to your types.

class Distance:
    def __init__(self, meters):
        self.meters = meters

    def __format__(self, spec):
        if spec == "km":
            return f"{self.meters / 1000:.2f}km"
        elif spec == "m":
            return f"{self.meters:.2f}m"
        elif spec == "cm":
            return f"{self.meters * 100:.1f}cm"
        else:
            return f"{self.meters}m"

d = Distance(5234)
>>> f"{d:km}"
'5.23km'
>>> f"{d:cm}"
'523400.0cm'
>>> f"{d}"
'5234m'

Python does not interpret "km" or "cm" — those specs are entirely custom. Your __format__ method decides how to handle every spec string. When you receive an unfamiliar spec, returning a default representation is the safest approach.

Edge Cases

Empty format spec: f"{obj}" (no colon) passes "" as format_spec. Your __format__ must handle this gracefully.

Compound specs: f"{obj:>10,.2f}" passes ">10,.2f" as the full string. You receive the complete spec and can parse it however you like.

Custom specs: Specs like "USD" or "km" are not interpreted by Python. They arrive as-is in format_spec. The standard numeric mini-language only applies when Python’s own types use __format__.

Return type enforcement: Python does not enforce that __format__ returns str. Returning something else will not raise an error until the formatted result is used — typically in a string context where it will fail. Always return a string.

See Also

  • __str__ — human-readable string representation with no formatting arguments
  • __hash__ — return an integer hash value for an object (used in sets and dict keys)