[Python-ideas] String formatting and namedtuple

spir denis.spir at free.fr
Fri Feb 13 10:03:59 CET 2009

Le Thu, 12 Feb 2009 23:29:33 -0500,
Terry Reedy <tjreedy at udel.edu> a écrit :

> Aahz wrote:
> > On Thu, Feb 12, 2009, George Sakkis wrote:
> >> On Thu, Feb 12, 2009 at 2:24 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> >>> PROPOSAL: Allow the simple case to stay simple.  Allow field names to be
> >>> omitted for all fields in a string and then default to 0, 1, ... so that
> >>> example above could be written as
> >>>
> >>>>>> msg = "{} == {}".format
> >>> Given that computers are glorified counting machines, it *is* a bit annoying
> >>> to be required to do the counting manually.  I think this is at least half
> >>> the objection to switching to .format.
> >> What happens when both empty and non-empty fields appear ? E.g. would
> >>
> >>     'I love {} with {1} and {} with {1}'.format('bacon', 'eggs', 'sausage')
> >>
> >> return 'I love bacon with eggs and eggs with eggs', or it would be
> >> smarter and see that 1 is used explicitly and skip over it, giving 'I
> >> love bacon with eggs and sausage with eggs' ?
> > 
> > I'd favor raising an exception.  Alternatively, we could do the
> > equivalent of what % formatting does, which would be the first option
> > (that is, '{#}' is considered equivalent to mapped interpolation in %
> > formatting).
> From
> http://bugs.python.org/issue5237
> """This proposal is currently all or nothing for simplicity of 
> description and presumed ease of implementation.  The patch to the doc 
> could then be "If all replacement fields are left blank, then sequential 
> indexes 0,1, ... will be automatically inserted." inserted after [Each 
> replacement field contains either the numeric index of a positional 
> argument, or the name of a keyword argument.].  Mixing blank and 
> non-blank specs would then be an error and raise an exception. """
> I think mixing implicit and explicit indexes would be confusing.  Mixing 
> implicit indexes and keywords could perhaps work, but I won't propose 
> that.  It would be a rare usage, while my goal is to make the common 
> case '%s' format as easy to write as it is now, by replacing '%s' with 
> '{}' [two keystrokes each].
> Terry Jan Reedy

Agree with the base {} proposal. Not really with forbidding mixing:
A side-advantage is that this principle is consistent with the tuple/dict opposition: tuple items are implicitely numbered.
Note that this is even more analog to positional vs keyword function arguments. So that there is probably no need to forbid {} and {name} in the same format string, as long as names came after positionally identified sub-strings. We need instead a rule stating that empty {} come first and that names comply with the common identifier pattern, in order to avoid conflicts with implicit indexes.


la vida e estranya

More information about the Python-ideas mailing list