The __format__() method
The __format__()
method is used by string.format()
as well as the format()
built-in function. Both of these interfaces are used to get presentable string versions of a given object.
The following are the two ways in which arguments will be presented to __format__()
:
someobject.__format__("")
: This happens when the application doesformat(someobject)
or something equivalent to"{0}".format(someobject)
. In these cases, a zero-length string specification was provided. This should produce a default format.someobject.__format__(specification)
: This happens when the application doesformat(someobject, specification)
or something equivalent to"{0:specification}".format(someobject)
.
Note that something equivalent to "{0!r}".format()
or "{0!s}".format()
doesn't use the __format__()
method. These use __repr__()
or __str__()
directly.
With a specification of ""
, a sensible response is return str(self)
. This provides an obvious consistency between the various string representations...