[Python-ideas] Have a "j" format option for lists
Chris Angelico
rosuav at gmail.com
Thu May 10 09:34:52 EDT 2018
On Thu, May 10, 2018 at 11:13 PM, Facundo Batista
<facundobatista at gmail.com> wrote:
>> I would like to see you flesh out the idea. In particular, I'd like to see you
>> address cases where:
>> 1. The underlying members in the collection are not strings. Besides the basic
>> types such as numbers, it would also be nice to be able to apply formats
>> recursively so that one can construct a string using the attributes of
>> members that are objects or items or other collections.
>
> I didn't think about this at the time. I have the feeling (not really
> well thought yet) that "recursive formatting" will complicate
> everything too much, that doing str() (as {} defaults to) on every
> object would fulfill most of the basic cases and keep this simple.
>
>
>> 2. The ability to handle collections other than simple lists or iterables, such
>> as dictionaries.
>
> Ideally, it will handle *any* iterable.
If it's to handle arbitrary iterables, it can't be the normal style of
"take this string, pass it to the object's __format__ method, and let
it interpret it". That's why I suggested a bang notation instead. We
have some already:
>>> x = "O'Really?"
>>> print(f"!s: {x!s} !r: {x!r}")
!s: O'Really? !r: "O'Really?"
Those markers apply to ANY object, and pass it through str() or repr()
respectively, before using any provided format string. A "!j" flag
could take an iterable, format each element using the given format,
and then join them. The letter "j" makes good sense then, as it
parallels str.join() - this would be broadly similar to
"...".join(format(...) for x in iter).
ChrisA
More information about the Python-ideas
mailing list