Formatter

MergedOptionStringFormatter is provided as a base class for creating a special formatter that can format strings using a MergedOptions object.

from delfick_project.option_merge import MergedOptionStringFormatter, MergedOptions

class Formatter(MergedOptionStringFormatter):
    passthrough_format_specs = ["env"]

    def special_format_field(self, obj, format_spec):
        if format_spec == "env":
            return f"${{{obj}}}"

m = MergedOptions.using({"a": {"b": 3}, "c": 5, "d": "{c}"})
formatted = Formatter(m, "a.b: {a.b}, d: {d} and c={c} and d={BLAH:env}").format()
assert formatted == "a.b: 3, d: 5 and c=5 and d=${BLAH}"

Instance Methods

class delfick_project.option_merge.formatter.MergedOptionStringFormatter(all_options, value, chain=None)

Resolve format options into a MergedOptions dictionary

format()

Format our value into all_options

special_format_field(obj, format_spec)

In this function you match against format_spec and return either a formatted version of obj or None.

class MyFormatter(MergedOptionStringFormatter):
    passthrough_format_specs = ["plus_one"]

    def special_format_field(obj, format_spec):
        if format_spec == "plus_one":
            return int(obj) + 1

formatted = MyFormatter({}, "{3:plus_one}").format()
assert formatted == 4

Note

If you want the formatted value as obj then don’t put your format_spec in the passthrough_format_specs list