[Python-3000] string.Formatter class

Ron Adam rrr at ronadam.com
Fri Aug 31 03:11:47 CEST 2007



Eric Smith wrote:
> Ron Adam wrote:
>>> get_field(field_name, args, kwargs, used_args)
>>> Given a field_name as returned by parse, convert it to an object to 
>>> be formatted.  The default version takes strings of the form defined 
>>> in the PEP, such as "0[name]" or "label.title".  It records which 
>>> args have been used in used_args.  args and kwargs are as passed in 
>>> to vformat.
>>
>> Rather than pass the used_args set out and have it modified in a 
>> different methods, I think it would be better to pass the arg_used 
>> back along with the object.  That keeps all the code that is involved 
>> in checking used args is in one method.  The arg_used value may be 
>> useful in other ways as well.
>>
>>      obj, arg_used = self.get_field(field_name, args, kwargs)
>>      used_args.add(arg_used)
> 
> I'm really not wild about either solution, but I suppose yours is less 
> objectionable than mine.  I'll check this change in tonight (before the 
> deadline).

Cool.  I looked at other possible ways, but this seemed to be the easiest 
to live with.  The alternative is to use an attributes to pass and hold 
values, but sense the Formatter class isn't a data class, that doesn't seem 
appropriate.

> I think you'd have to say:
> 
> if args_used is not None:
>    used_args.add(args_used)
> 
> as it's possible that the field was not derived from the args or kwargs.

How?  From what I can see an exception would be raised in the get_value method.

When would I ever want to get a None for args_used?


>> I wonder if this is splitting things up a bit too finely?  If the 
>> format function takes a conversion argument, it makes it possible to 
>> do everything by overriding format_field.
>>
>>     def format_field(self, value, format_spec, conversion):
>>         return format(value, format_spec, conversion)
>>
>>
>> Adding this to Talins suggestion, the signature of format could be...
>>
>>     format(value, format_spec="", conversion="")
> 
> But this conflates conversions with formatting, which the PEP takes 
> pains not to do.  I'd rather leave them separate, but I'll let Talin 
> make the call.

Yes the PEP is pretty specific on the format() function signature.


Cheers,
    Ron















More information about the Python-3000 mailing list