[Python-ideas] new format spec for iterable types

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Tue Sep 8 14:55:43 CEST 2015

On 08.09.2015 14:24, Andrew Barnert via Python-ideas wrote:
 > 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.

Not sure what happened to the indentation in the posted code. Here's 
another attempt copy pasting from working code as I thought I had done 
before (sorry for the inconvenience):

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)
             raise TypeError()

head = 99
data = myList(range(10))
s = '{}, {:*, }'.format(head, data)
# or
s2 = '{}{sep}{:*{sep}}'.format(head, data, sep=', ')
# 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Does that make things clearer?

More information about the Python-ideas mailing list