Curious Omission In New-Style Formats

Ian Kelly ian.g.kelly at gmail.com
Mon Jul 11 21:16:03 EDT 2016


On Mon, Jul 11, 2016 at 5:47 PM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Ethan Furman wrote:
>>
>> I will readily admit to not having a maths degree, and so of course to me
>> saying the integer 123 has a precision of 5, 10, or 99 digits seems like
>> hogwash to me.
>
>
> Seems to me insisting that the number after the dot be
> called "precision" in all cases is imposing a foolish
> consistency.
>
> There's a third thing that %-formats use it for as well:
> for a string it means the maximum number of characters
> to include.
>
> To my way of thinking, the format string just lets you
> specify uop to two numbers, the interpratation or wnich
> is up to toe format concerned.

The builtin types strive for consistency with each other and with
printf-style formats, but ultimately the parsing of the format spec is
entirely at the whim of the __format__ method of the type being
formatted. You could make it a Turing-complete mini-language if you
liked.

py> class Foo:
...     def __format__(self, spec):
...         return str(eval(spec)(self))
...
py> '{:id}'.format(Foo())
'139869336090384'
py> '{:repr}'.format(Foo())
'<__main__.Foo object at 0x7f35de17b7b8>'
py> '{:lambda x: x == 42}'.format(Foo())
'False'



More information about the Python-list mailing list