Kyle
Kyle

Reputation: 2894

Proper use of __format__

I have a class that defines __str__ to return the integer value in hex and a __format__ to return the value formatted with the user's format spec:

class MyClass:
    def __init__(self, value: int):
        self._value = value

    def __str__(self):
        return '{:04X}'.format(self._value)

    def __format__(self, format_spec):
        return format_spec.format(self._value)

So I would expect:

'{:04X}'.format(MyClass(10)) == '000A'

and

 str(MyClass(10)) == '000A'

but the str.format call just returns the format spec, 04X. What am I doing wrong?

Upvotes: 3

Views: 2914

Answers (1)

MSeifert
MSeifert

Reputation: 152725

Only the spec (the part in the curly braces after the colon) is passed to the __format__ method, in your case that's '04X'. That contains no placeholders so calling format on it will simply return the '04X' again.

In case you want to "pass on" the format_spec to self._value then you need to do that explicitly, for example using the built-in format function:

class MyClass:
    def __init__(self, value: int):
        self._value = value

    def __str__(self):
        return '{:04X}'.format(self._value)

    def __format__(self, format_spec):
        return format(self._value, format_spec)
>>> '{:04X}'.format(MyClass(10))
'000A'

Upvotes: 4

Related Questions