[Python-ideas] new format spec for iterable types

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Sep 8 20:15:24 CEST 2015

On 8 September 2015 at 17:27, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> A technical comment: you don't actually need the '*' for myList
> (although I guess you find it useful to get an error rather than line
> noise as a separator if it isn't present?)

I think Wolfgang wants it to work with any iterable rather than his
own custom type (at least that's what I'd want). For that to work it
would be better if it was handled by the format method itself rather
than every iterable's __format__ method. Then it could work with
generators, lists, tuples etc.

> On the basic idea: if this can be generalized a bit so that
>     head = 99
>     data = range(10)                # optimism!
>     s = '{:.1f}, {:.1f*, }'.format(head, data)
> produces
>     s == '99.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0'
> then I'd be a lot more attracted to it.

ATM the colon separates the part of the format element that is
interpreted by the format method to find the formatted object from the
part that is passed to the __format__ method of the formatted object.
Perhaps an additional colon could be used to separate the separator
for when the formatted object is an iterable so that

     'foo {name:<fmt>:<sep>} bar'.format(name=<expr>)

could become

    'foo {_name} bar'.format(_name = '<sep>'.join(format(o, '<fmt>')
for o in <expr>))

The example would then be

    >>> '{:.1f}, {:.1f:, }'.format(99, range(10))
    '99.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0'


More information about the Python-ideas mailing list