[Python-ideas] new format spec for iterable types

Andrew Barnert abarnert at yahoo.com
Wed Sep 9 23:28:46 CEST 2015


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.

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.



More information about the Python-ideas mailing list