Provides a class that is capable of basic bytestring templating, similar to the str.format() method. This is needed in Python 3 before 3.5+, but should work in all supported versions.

This class does the heavy lifting (a re.finditer() loop) during construction, so it is optimal to instantiate it once and then re-use format().

class slimta.util.bytesformat.BytesFormat(template[, mode='ignore'])

Bases: object

Wraps a bytestring in a class with a format() method similar to str.format().

During construction, the template string is scanned for matching {...} pairs that contain only characters that match the \w regular expression. In the format() method, these {...} are replaced with a matching argument’s value, if an argument matches, or the action specified by mode happens when it does not match

To match format() arguments, you may use a positional argument’s number (e.g. {0}) or a keyword argument’s key (e.g. {recipient}). Additional formatting options are not supported.

  • template (bytes) – The template bytestring.
  • mode – If 'ignore', any {...} that does not match a format() argument is left in place as-is. If 'remove', these {...} are replaced with an empty string. If 'strict', these {...} will cause KeyError or IndexError exceptions.
format([*args[, **kwargs]])

Substitutes in the given positional and keyword arguments into the original template string, replacing occurrences of {...} with the correct argument’s value.

Return type:bytes