Skip to content

template_replace

String template substitution with custom delimiters and lookup functions.

This module provides :func:template_replace which substitutes placeholders in a string using a customizable delimiter, supporting default values (${ID:DEFAULT}) and pluggable lookup functions for dictionary, attribute, or other value resolution strategies.

defval_lookup(vals, default)

Create a lookup function falling back to a default value.

Parameters:

Name Type Description Default
vals

The dictionary of key/value pairs.

required
default

Default value used when a key is missing; when None the missing placeholders resolve to ''.

required

Returns:

Type Description

A lookup function taking (key, defval).

Source code in py_misc_utils/template_replace.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def defval_lookup(vals, default):
  """Create a lookup function falling back to a default value.

  Args:
    vals: The dictionary of key/value pairs.
    default: Default value used when a key is missing; when None the
      missing placeholders resolve to '<delim><key>'.

  Returns:
    A lookup function taking (key, defval).
  """

  def lookup_fn(key, defval=None):
    """Resolve a key from the dictionary, falling back to the default.

    Args:
      key: The lookup key.
      defval: Optional default value returned when the key is missing.

    Returns:
      The value, the default value, or the missing marker.
    """
    value = vals.get(key, defval)
    if value is None:
      return f'${key}' if default is None else default

    return value

  return lookup_fn

attr_lookup(obj, default)

Create a lookup function resolving keys as object attributes.

Parameters:

Name Type Description Default
obj

Object whose attributes provide the substitution values.

required
default

Default value used when an attribute is missing; when None the missing placeholders resolve to ''.

required

Returns:

Type Description

A lookup function taking (key, defval).

Source code in py_misc_utils/template_replace.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def attr_lookup(obj, default):
  """Create a lookup function resolving keys as object attributes.

  Args:
    obj: Object whose attributes provide the substitution values.
    default: Default value used when an attribute is missing; when None
      the missing placeholders resolve to '<delim><key>'.

  Returns:
    A lookup function taking (key, defval).
  """

  def lookup_fn(key, defval=None):
    """Resolve a key as an object attribute, falling back to the default.

    Args:
      key: The attribute name to look up.
      defval: Optional default value returned when the attribute is
        missing.

    Returns:
      The attribute value, the default value, or the missing marker.
    """
    value = getattr(obj, key, defval)
    if value is None:
      return f'${key}' if default is None else default

    return value

  return lookup_fn

template_replace(st, vals=None, lookup_fn=None, delim=None, misses_ok=None)

Substitute placeholders in a template string.

Placeholders use the delimiter (default '$') and may include default values: ${ID:DEFAULT_VALUE}.

Parameters:

Name Type Description Default
st

The template string.

required
vals

Optional dictionary of substitutions (used if lookup_fn is None).

None
lookup_fn

Optional custom lookup function taking (key, defval).

None
delim

Optional delimiter character; defaults to '$'.

None
misses_ok

If True, unresolved placeholders are left as-is instead of raising KeyError.

None

Returns:

Type Description

The substituted string.

Example
from py_misc_utils import template_replace as tr

print(tr.template_replace('user=$user', vals={'user': 'ada'}))  # user=ada
print(tr.template_replace('${user}', vals={'user': 'ada'}))  # ada

# A per-key default is used when the key is missing:
print(tr.template_replace('${mode:fine}', vals={}))  # fine

# A custom delimiter:
print(tr.template_replace('a=@a@', delim='@', vals={'a': 1}))  # a=1@

# Unresolved placeholders raise KeyError unless misses_ok is set:
print(tr.template_replace('$a$b', vals={'a': 1}, misses_ok=True))  # 1$b
Source code in py_misc_utils/template_replace.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def template_replace(st, vals=None, lookup_fn=None, delim=None, misses_ok=None):
  """Substitute placeholders in a template string.

  Placeholders use the delimiter (default '$') and may include default
  values: ${ID:DEFAULT_VALUE}.

  Args:
    st: The template string.
    vals: Optional dictionary of substitutions (used if lookup_fn is None).
    lookup_fn: Optional custom lookup function taking (key, defval).
    delim: Optional delimiter character; defaults to '$'.
    misses_ok: If True, unresolved placeholders are left as-is instead of
      raising KeyError.

  Returns:
    The substituted string.

  Example:
    from py_misc_utils import template_replace as tr

    print(tr.template_replace('user=$user', vals={'user': 'ada'}))  # user=ada
    print(tr.template_replace('${user}', vals={'user': 'ada'}))  # ada

    # A per-key default is used when the key is missing:
    print(tr.template_replace('${mode:fine}', vals={}))  # fine

    # A custom delimiter:
    print(tr.template_replace('a=@a@', delim='@', vals={'a': 1}))  # a=1@

    # Unresolved placeholders raise KeyError unless misses_ok is set:
    print(tr.template_replace('$a$b', vals={'a': 1}, misses_ok=True))  # 1$b
  """
  delim = delim or '$'
  misses_ok = False if misses_ok is None else misses_ok

  class Template(string.Template):
    """string.Template subclass accepting ${ID:DEFAULT} placeholders."""

    # Allow for brace ID with the format ${ID:DEFAULT_VALUE}.
    braceidpattern = r'((?a:[_a-z][_a-z0-9]*)(:[^}]*)?)'
    delimiter = delim

  if lookup_fn is None:
    lookup_fn = _dict_lookup_fn(vals, delim, misses_ok)

  return Template(st).safe_substitute(_FnDict(lookup_fn))