[Python-3000] Format specifier proposal
Ron Adam
rrr at ronadam.com
Thu Aug 16 03:07:02 CEST 2007
Jim Jewett wrote:
> On 8/15/07, Ron Adam <rrr at ronadam.com> wrote:
>
>> After each term is returned from the __format__ call, the results
>> __format__ method is called with the next specifier. GetTime.__format__
>> returns a string. str.__format__, aligns it. A nice left to right
>> sequence of events.
>
> Is this a pattern that objects should normally follow, or a convention
> enforced by format itself? In other words, does
>
> "{0:abc,def,ghi}".format(value)
>
> mean
>
> # Assume value.__format__ will delegate properly, to
> # result1.__format__("def,ghi")
> #
> # There are some surprises when a trailing field size gets ignored by
> # value.__class__.
> #
> # Are infinite loops more likely?
> value.__format__("abc,def,ghi")
>
> or
>
> # The separator character (","?) gets hard to use in format strings...
> value.__format__("abc").__format__("def").__format__("ghi")
It would have to be this version. There isn't any way for the vformat
method (*) to decide which ',' belongs where unless you create some strict
and awkward rules about when you can use comma's and when you can't.
* vformat is the method described in the pep responsible for calling
format() with each value and specifier. So it is where the chaining is done.
Currently I have only the following for this part, but it could be more
sophisticated.
value = self.get_value(key, args, kwargs)
for term in spec.split(','):
value = format(value, term)
There are two ways around this, one is to have a comma escape sequence such
as '\,'. Then after it split, it can replace the '\,' with ',' and then
call format with the specifier with the un-escaped commas.
Another way might be to be able to designate an alternative separator in
some way. {0:|:abc|def,ghi} Where :sep: is the separator to use other
than comma. Or :: to force a single term with no chaining. Or some other
syntax might work? <shurg> It's not an impossible problem to solve.
The idea is __format__ methods only need to be concerned with their part.
They shouldn't have to parse some other objects specifier and pass it
along. (But you can still do that if you really want to.)
Cheers,
Ron
More information about the Python-3000
mailing list