New Python 3.0 string formatting - really necessary?

Aaron Brady castironpi at gmail.com
Mon Dec 22 04:42:35 EST 2008


On Dec 21, 8:42 pm, MRAB <goo... at mrabarnett.plus.com> wrote:
> Aaron Brady wrote:
> > On Dec 21, 6:14 pm, MRAB <goo... at mrabarnett.plus.com> wrote:
snip
> >> Yes, I suggested that earlier, but it isn't needed because you can
> >> create a format object with "Format(string)". However, most of the time
> >> you won't bother to create a format object explicitly because of:
>
> >> class str(object):
> >>      def __mod__(self, value):
> >>          return Format(self) % value
>
> >>>>>> f = f"%r %i"
> >>>>>> type(f)
> >>> <type 'Format'>
> >>  >>> # Explicitly
> >>  >>> f = Format("%r %i")
> >>  >>> f
> >> <Format '%r %i'>
> >>  >>> f % (2, 3, 4)
> >> <Format '(2, 3, 4) %i'>
>
> >>  >>> # Implicitly, relying on the __mod__ method of str
> >>  >>> f = "%r %i"
> >>  >>> f
> >> '%r %i'
> >>  >>> f % (2, 3, 4)
> >> <Format '(2, 3, 4) %i'>
>
> >> I'd also like to add that there's nothing to prevent format objects from
> >> having other methods where multiple placeholders can be filled in one call:
>
> >>  >>> # By position
> >>  >>> f = Format("%r %i")
> >>  >>> f
> >> <Format '%r %i'>
> >>  >>> f.fill([(2, 3, 4), 1])
> >> '(2, 3, 4) 1'
>
> >>  >>> # By name
> >>  >>> f = Format("%{tuple}r %{int}i")
> >>  >>> f
> >> <Format '%{tuple}r %{int}i'>
> >>  >>> f.fill({"tuple": (2, 3, 4), "int": 1})
> >> '(2, 3, 4) 1'
>
> > You're choosing to favor the '.chain()' method over the '.fill()'
> > method for the behavior of '%'.  I don't think you've justified it
> > though.
>
> >>>> Format( "%r %i" ).chain( ( 2, 3, 4 ) ).chain( 0 )
> > '(2, 3, 4) 0'
> >>>> Format( "%r %i" ).fill( ( 2, 3, 4 ), 0 )
> > '(2, 3, 4) 0'
>
> > Plus, I almost think we've almost attained defeating the purpose.
>
> The disadvantage of the chaining method is that it's positional,
> left-to-right. For the purposes of i18n you want tagged placeholders,
> whether they be integers or names. I think... OK, if the placeholders
> include a positional tag, eg "%(0)s %(1)s", then they could be filled in
> according to _that_ order. Not sure about named placeholders, though.
> Perhaps, like at present, if a dict is given to a format with named
> placeholders then several placeholders could be filled, the problem
> being how to fill a _single_ named placeholder with a dict.

Just pass a keyword argument to chain.

>>> Format( "%(tup)r %(int_)i" ).chain( tup= ( 2, 3, 4 ) ).chain( int_= 0 )
'(2, 3, 4) 0'

You might want to call it 'fchain' or 'chainf'.



More information about the Python-list mailing list