Modified parsing of format strings, so that we always return

a tuple (literal, field_name, format_spec, conversion).

literal will always be a string, but might be of zero length.
field_name will be None if there is no markup text
format_spec will be a (possibly zero length) string if
  field_name is non-None
conversion will be a one character string, or None

This makes the Formatter class, and especially it's parse()
method, easier to understand.

Suggestion was by Jim Jewett, inspired by the "tail" of an
elementtree node.

Also, fixed a reference leak in fieldnameiter_next.
This commit is contained in:
Eric Smith 2007-08-29 03:22:59 +00:00
parent 9600f93db6
commit 625cbf28ee
2 changed files with 170 additions and 159 deletions

View file

@ -212,7 +212,13 @@ class Formatter:
result = []
for literal_text, field_name, format_spec, conversion in \
self.parse(format_string):
if literal_text is None:
# output the literal text
if literal_text:
result.append(literal_text)
# if there's a field, output it
if field_name is not None:
# this is some markup, find the object and do
# the formatting
@ -224,9 +230,7 @@ class Formatter:
# format the object and append to the result
result.append(self.format_field(obj, format_spec))
else:
# this is literal text, use it directly
result.append(literal_text)
self.check_unused_args(used_args, args, kwargs)
return ''.join(result)
@ -263,6 +267,11 @@ class Formatter:
# returns an iterable that contains tuples of the form:
# (literal_text, field_name, format_spec, conversion)
# literal_text can be zero length
# field_name can be None, in which case there's no
# object to format and output
# if field_name is not None, it is looked up, formatted
# with format_spec and conversion and then used
def parse(self, format_string):
return format_string._formatter_parser()