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:

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 to False.

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

get_value()[source]

Computes, optionally caches, and returns the value of the func. If get_value() has been called before, a cached value may be returned depending on the cache_value option passed to the constructor.

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 explict, numbered positional references. To disable this behavior set resolve_pos to False.

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.

set_conv(conv)[source]

There are only two built-in converters: s and r. They are somewhat rare and appearlike "{ref!r}".

set_fname(fname)[source]

Set the field name.

set_fspec(fspec)[source]

Set the field spec.