[Python-ideas] Have a "j" format option for lists
Eric V. Smith
eric at trueblade.com
Wed May 9 10:29:22 EDT 2018
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
Eric
More information about the Python-ideas
mailing list