[Python-ideas] Have a "j" format option for lists

Paul Moore p.f.moore at gmail.com
Wed May 9 10:41:44 EDT 2018


On 9 May 2018 at 15:29, Eric V. Smith <eric at trueblade.com> wrote:
> On 5/9/18 10:01 AM, Paul Moore wrote:
>>
>> On 9 May 2018 at 14:49, Eric V. Smith <eric at trueblade.com> wrote:
>>>
>>> I would object to changing the format machinery. Any format spec should
>>> be
>>> interpreted by some object's __format__ method.
>>
>>
>> Agreed. In theory this is a nice idea, but the way formatting is
>> implemented (and the fact that join is a method on strings taking an
>> arbitrary iterable as an argument) means that it's a bad fit for the
>> format mini-language.
>>
>> I don't think the improved convenience is sufficient to warrant the
>> change that would be required in practice. (But if someone found a way
>> to make it work *without* changes to the underlying format machinery,
>> that would be a different matter...)
>
>
> Well, since you asked, let's combine this with dataclasses, because we can!
>
> from dataclasses import dataclass
> from typing import List
>
> @dataclass
> class Join:
>     o: List[str]  # or similar
>     def __format__(self, spec):
>         return spec.join(self.o)
>
> l = ['a', 'b']
>
> print('{:, }'.format(Join(l)))
> print(f'{Join(l):-}')
>
> Gives:
> a, b
> a-b

:-)

Sorry, I should have been clearer. Given that

    print('{}'.format(', '.join(l)))

isn't that difficult, at least for me the attraction of the proposal
was the possibility of not having to wrap the argument (whether in a
function call, or in a custom class). But the

    print(f'{Join(l):-}')

approach is certainly cleaner looking than print(f'{", ".join(l)}').

Paul


More information about the Python-ideas mailing list