[Python-ideas] new format spec for iterable types
Oscar Benjamin
oscar.j.benjamin at gmail.com
Tue Sep 8 15:41:39 CEST 2015
On 8 September 2015 at 13:24, Andrew Barnert via Python-ideas
<python-ideas at python.org> wrote:
> Wolfgang wrote:
>> A quick and dirty illustration in Python:
>>
>> class myList(list):
>> def __format__ (self, fmt=''):
>> if fmt == '':
>> return str(self)
>> if fmt[0] == '*':
>> sep = fmt[1:] or ' '
>> return sep.join(format(e) for e in self)
>> else:
>> raise TypeError()
>>
>> head = 99
>> data = myList(range(10))
>> s = '{}, {:*, }'.format(head, data)
>> # or
>> s2 = '{}{sep}{:*{sep}}'.format(head, data, sep=', ')
>> print(s)
>> print(s2)
>> # 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
>
> Formatting positional argument #2 with *{sep} as the format specifier makes no sense to me. Even knowing what you're trying to do, I can't understand what *(', ') is going to pass to data.__format__, or why it should do what you want. What is the * supposed to mean there? Is it akin to *args in a function call expression, so you get ',' and ' ' as separate positional arguments? If so, how does the fmt[1] do anything useful? It seems like you would be using [' '] as the separator, and in not sure what that would do that you'd want.
The *{sep} surprised me until I tried
>>> '{x:.{n}f}'.format(x=1.234567, n=2)
'1.23'
So format uses a two-level pass over the string for nested curly
brackets (I tried a third level of nesting but it didn't work).
So following it through:
'{}{sep}{:*{sep}}'.format(head, data, sep=', ')
'{}, {:*, }'.format(head, data)
'{}, {}'.format(head, format(data, '*, '))
'{}, {}'.format(head, ', '.join(format(e) for e in data))
'99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9'
Unfortunately there's no way to also give a format string to the inner
format call format(e) if I wanted to e.g. format those numbers in hex.
--
Oscar
More information about the Python-ideas
mailing list