formatutils
- str.format()
toolbox¶
PEP 3101 introduced the str.format()
method, and what
would later be called “new-style” string formatting. For the sake of
explicit correctness, it is probably best to refer to Python’s dual
string formatting capabilities as bracket-style and
percent-style. There is overlap, but one does not replace the
other.
- Bracket-style is more pluggable, slower, and uses a method.
- Percent-style is simpler, faster, and uses an operator.
Bracket-style formatting brought with it a much more powerful toolbox,
but it was far from a full one. str.format()
uses more powerful
syntax, but the tools and idioms for working with
that syntax are not well-developed nor well-advertised.
formatutils
adds several functions for working with bracket-style
format strings:
DeferredValue
: Defer fetching or calculating a value until format time.get_format_args()
: Parse the positional and keyword arguments out of a format string.tokenize_format_str()
: Tokenize a format string into literals andBaseFormatField
objects.construct_format_field_str()
: Assists in progammatic construction of format strings.infer_positional_format_args()
: Converts anonymous references in 2.7+ format strings to explicit positional arguments suitable for usage with Python 2.6.
-
class
boltons.formatutils.
DeferredValue
(func, cache_value=True)[source]¶ DeferredValue
is a wrapper type, used to defer computing values which would otherwise be expensive to stringify and format. This is most valuable in areas like logging, where one would not want to waste time formatting a value for a log message which will subsequently be filtered because the message’s log level was DEBUG and the logger was set to only emit CRITICAL messages.The :class:
DeferredValue
is initialized with a callable that takes no arguments and returns the value, which can be of any type. By default DeferredValue only calls that callable once, and future references will get a cached value. This behavior can be disabled by setting cache_value toFalse
.Parameters: - func (function) – A callable that takes no arguments and computes the value being represented.
- cache_value (bool) – Whether subsequent usages will call func
again. Defaults to
True
.
>>> import sys >>> dv = DeferredValue(lambda: len(sys._current_frames())) >>> output = "works great in all {0} threads!".format(dv)
PROTIP: To keep lines shorter, use:
from formatutils import DeferredValue as DV
-
boltons.formatutils.
get_format_args
(fstr)[source]¶ Turn a format string into two lists of arguments referenced by the format string. One is positional arguments, and the other is named arguments. Each element of the list includes the name and the nominal type of the field.
# >>> get_format_args(“{noun} is {1:d} years old{punct}”) # ([(1, <type ‘int’>)], [(‘noun’, <type ‘str’>), (‘punct’, <type ‘str’>)])
# XXX: Py3k >>> get_format_args(“{noun} is {1:d} years old{punct}”) == ([(1, int)], [(‘noun’, str), (‘punct’, str)]) True
-
boltons.formatutils.
tokenize_format_str
(fstr, resolve_pos=True)[source]¶ Takes a format string, turns it into a list of alternating string literals and
BaseFormatField
tokens. By default, also infers anonymous positional references into explicit, numbered positional references. To disable this behavior set resolve_pos toFalse
.
-
boltons.formatutils.
construct_format_field_str
(fname, fspec, conv)[source]¶ Constructs a format field string from the field name, spec, and conversion character (
fname
,fspec
,conv
). See Python String Formatting for more info.
-
boltons.formatutils.
infer_positional_format_args
(fstr)[source]¶ Takes format strings with anonymous positional arguments, (e.g., “{}” and {:d}), and converts them into numbered ones for explicitness and compatibility with 2.6.
Returns a string with the inferred positional arguments.
-
class
boltons.formatutils.
BaseFormatField
(fname, fspec='', conv=None)[source]¶ A class representing a reference to an argument inside of a bracket-style format string. For instance, in
"{greeting}, world!"
, there is a field named “greeting”.These fields can have many options applied to them. See the Python docs on Format String Syntax for the full details.
-
fstr
¶ The current state of the field in string format.
-