[Python-ideas] new format spec for iterable types

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Thu Sep 10 00:03:05 CEST 2015


On 09.09.2015 23:28, Andrew Barnert via Python-ideas wrote:
> On Sep 9, 2015, at 06:41, Wolfgang Maier <wolfgang.maier at biologie.uni-freiburg.de> wrote:
>>
>> 3)
>> Finally, the alternative idea of having the new functionality handled by a new !converter, like:
>>
>> "List: {0!j:,}".format([1.2, 3.4, 5.6])
>>
>> I considered this idea before posting the original proposal, but, in addition to requiring a change to str.format (which would need to recognize the new token), this approach would need either:
>>
>> - a new special method (e.g., __join__) to be implemented for every type that should support it, which is worse than for my original proposal or
>>
>> - the str.format method must react directly to the converter flag, which is then no different to the above solution just that it uses !j instead of *. Personally, I find the * syntax more readable, plus, the !j syntax would then suggest that this is a regular converter (calling a special method of the object) when, in fact, it is not.
>> Please correct me, if I misunderstood something about this alternative proposal.
>
> But the format method already _does_ react directly to the conversion flag. As the docs say, the "type coercion" (call to str, repr, or ascii) happens before formatting, and then the __format__ method is called on the result. A new !j would be a "regular converter"; it just calls a new join function (which returns something whose __format__ method then does the right thing) instead of the str, repr, or ascii functions.
>

Ah, I see! Thanks for correcting me here. Somehow, I had the mental 
picture that the format converters would call the object's __str__ and 
__repr__ methods directly (and so you'd need an additional __join__ 
method for the new converter), but that's not the case then.

> And random's custom converter idea would work similarly, except that presumably his !join would specify a function registered to handle the "join" conversion in some way rather than being hardcoded to a builtin.
>

How would such a registration work (sorry, I haven't had the time to 
search the list for his previous mention of this idea)? A new builtin 
certainly won't fly.

Thanks,
Wolfgang



More information about the Python-ideas mailing list