Updates to PEP3101. Adds explicit prohibitions on edge cases that were previously undefined by the PEP. Better specifies how default formatting (empty format specifier string) behaves. Also fixed several bugs in the examples.

This commit is contained in:
Talin 2007-08-23 23:16:30 +00:00
parent f9bb346a22
commit fb6c09e47b
1 changed files with 41 additions and 28 deletions

View File

@ -212,6 +212,11 @@ Format Specifiers
"{0:{1}}".format(a, b, c)
These 'internal' replacement fields can only occur in the format
specifier part of the replacement field. Internal replacement fields
cannot themselves have format specifiers. This implies also that
replacement fields cannot be nested to arbitrary levels.
Note that the doubled '}' at the end, which would normally be
escaped, is not escaped in this case. The reason is because
the '{{' and '}}' syntax for escapes is only applied when used
@ -231,10 +236,10 @@ Standard Format Specifiers
standard set of format specifiers are used. These are similar
in concept to the format specifiers used by the existing '%'
operator, however there are also a number of differences.
The general form of a standard format specifier is:
[[fill]align][sign][width][.precision][type]
[[fill]align][sign][0][width][.precision][type]
The brackets ([]) indicate an optional element.
@ -246,7 +251,8 @@ Standard Format Specifiers
available space.
'=' - Forces the padding to be placed after the sign (if any)
but before the digits. This is used for printing fields
in the form '+000000120'.
in the form '+000000120'. This alignment option is only
valid for numeric types.
'^' - Forces the field to be centered within the available
space.
@ -255,13 +261,11 @@ Standard Format Specifiers
that the alignment option has no meaning in this case.
The optional 'fill' character defines the character to be used to
pad the field to the minimum width. The alignment flag must be
supplied if the character is a number other than 0 (otherwise the
character would be interpreted as part of the field width
specifier). A zero fill character without an alignment flag
implies an alignment type of '='.
pad the field to the minimum width. The fill character, if present,
must be followed by an alignment flag.
The 'sign' element can be one of the following:
The 'sign' option is only valid for number types, and can be one of
the following:
'+' - indicates that a sign should be used for both
positive as well as negative numbers
@ -269,10 +273,14 @@ Standard Format Specifiers
numbers (this is the default behavior)
' ' - indicates that a leading space should be used on
positive numbers
'width' is a decimal integer defining the minimum field width. If
not specified, then the field width will be determined by the
content.
If the width field is preceded by a zero ('0') character, this enables
zero-padding. This is equivalent to an alignment type of '=' and a
fill character of '0'.
The 'precision' is a decimal number indicating how many digits
should be displayed after the decimal point in a floating point
@ -281,9 +289,6 @@ Standard Format Specifiers
the field content. The precision is ignored for integer conversions.
Finally, the 'type' determines how the data should be presented.
If the type field is absent, an appropriate type will be assigned
based on the value to be formatted ('d' for integers and longs,
'g' for floats and decimals, and 's' for everything else.)
The available integer presentation types are:
@ -296,6 +301,7 @@ Standard Format Specifiers
case letters for the digits above 9.
'X' - Hex format. Outputs the number in base 16, using upper-
case letters for the digits above 9.
'' (None) - the same as 'd'
The available floating point presentation types are:
@ -316,11 +322,9 @@ Standard Format Specifiers
number separator characters.
'%' - Percentage. Multiplies the number by 100 and displays
in fixed ('f') format, followed by a percent sign.
For non-numeric types, there's only one presentation type, 's', which
does nothing - its only purpose is to ease the transition from the
old '%' style formatting.
'' (None) - similar to 'g', except that it prints at least one
digit after the decimal point.
Objects are able to define their own format specifiers to
replace the standard ones. An example is the 'datetime' class,
whose format specifiers might look something like the
@ -328,6 +332,11 @@ Standard Format Specifiers
"Today is: {0:a b d H:M:S Y}".format(datetime.now())
For all built-in types, an empty format specification will produce
the same result as would have been produced by calling str(value).
It is recommended that objects defining their own format specifiers
follow this convention as well.
Explicit Conversion Flag
@ -336,16 +345,20 @@ Explicit Conversion Flag
formatting behavior, and format the value as if it were a more
generic type. Currently, two explicit conversion flags are
recognized:
!r - convert the value to a string using repr().
!s - convert the value to a string using str().
These flags are typically placed before the format specifier:
These flags are placed before the format specifier:
"{0!r:20}".format("Hello")
In the preceding example, the string "Hello" will be printed, with quotes,
in a field of at least 20 characters width.
A custom Formatter class can define additional conversion flags.
The built-in formatter will raise a ValueError if an invalid
conversion flag is specified.
Controlling Formatting on a Per-Type Basis
@ -486,8 +499,8 @@ Formatter Methods
if desired. The arguments to this function is the set of all argument
keys that were actually referred to in the format string (integers for
positional arguments, and strings for named arguments), and a reference
to the args and kwargs that was passed to vformat. The intersection
of these two sets will be the set of unused args. 'check_unused_args'
to the args and kwargs that was passed to vformat. The set of unused
args can be calculated from these parameters. 'check_unused_args'
is assumed to throw an exception if the check fails.
'format_field' simply calls the global 'format' built-in. The method
@ -510,7 +523,7 @@ Formatter Methods
field_spec, _, format_spec = token.partition(":")
# Check for explicit type conversion
field_spec, _, explicit = field_spec.partition("!")
explicit, _, field_spec = field_spec.rpartition("!")
# 'first_part' is the part before the first '.' or '['
# Assume that 'get_first_part' returns either an int or
@ -562,11 +575,11 @@ Customizing Formatters
One common desire is to support a 'default' namespace, so that
you don't need to pass in keyword arguments to the format()
method, but can instead use values in a pre-existing namespace.
This can easily be done by overriding get_named() as follows:
This can easily be done by overriding get_value() as follows:
class NamespaceFormatter(Formatter):
def __init__(self, namespace={}, flags=0):
Formatter.__init__(self, flags)
def __init__(self, namespace={}):
Formatter.__init__(self)
self.namespace = namespace
def get_value(self, key, args, kwds):