kwutil.partial_format module¶
Format strings in a bash-like way with subtemplate().
Partially format python format strings with variables that exist using
partial_format().
- kwutil.partial_format.partial_format(format_string, *args, **kwargs)[source]¶
A solution to the partial string formatting problem.
Taken from [SO11283961], which is a modification of the stdlib string.Formatter code.
- Parameters:
format_string (str) – the templated string to be formatted
*args – positional replacements
**kwargs – key value replacements
- Returns:
the format string with only the specified parts replaced.
- Return type:
Example
>>> from kwutil.partial_format import partial_format >>> format_string = '{foo} + {bar} = {baz}' >>> args = tuple() >>> kwargs = dict(bar=3) >>> partial_format(format_string, *args, **kwargs) '{foo} + 3 = {baz}'
References
[SO11283961] https://stackoverflow.com/questions/11283961/partial-string-formatting
- class kwutil.partial_format._PartialFormatter[source]¶
Bases:
FormatterA modified string formatter that handles a partial set of format args/kwargs.
- kwutil.partial_format.subtemplate(*args, **kwargs)[source]¶
Substitutes variables into a templated string.
Similar to format, replaces variables with bash-like dollar sign patterns (e.g. $VARNAME or ${VARNAME}).
- Parameters:
text (str) – the templated text
subs (dict | None) – a dictionary of substitutions
**kwargs – other substitutions
- Returns:
formatted text. Unspecified variables are left unchanged.
- Return type:
Notes
Order of precedence from lowest to highest goes: subs, kwargs
Example
>>> from kwutil.partial_format import * # NOQA >>> import ubelt as ub >>> text = ub.codeblock( >>> ''' >>> The $SUBJECT $VERB the $OBJECT >>> ''') >>> print(subtemplate(text, SUBJECT='dog', OBJECT='food')) The dog $VERB the food >>> print(subtemplate(text, SUBJECT='dog', VERB='eats', OBJECT='food')) The dog eats the food >>> print(subtemplate(text, {'SUBJECT': 'dude'}, SUBJECT='dog')) The dog $VERB the $OBJECT
- kwutil.partial_format.fsubtemplate(*args, **kwargs)[source]¶
Like subtemplate, but uses the current local variable context
- Parameters:
text (str) – the templated text
subs (dict | None) – a dictionary of substitutions
**kwargs – other substitutions
- Returns:
formatted text. Unspecified variables are left unchanged.
- Return type:
Notes
Order of precedence from lowest to highest goes: locals, subs, kwargs
Example
>>> from kwutil.partial_format import * # NOQA >>> import ubelt as ub >>> text = ub.codeblock( >>> ''' >>> The $SUBJECT $VERB the $OBJECT >>> ''') >>> SUBJECT = 'dude' >>> print(fsubtemplate(text, OBJECT='food')) The dude $VERB the food >>> print(fsubtemplate(text, SUBJECT='dog', OBJECT='food')) The dog $VERB the food >>> print(fsubtemplate(text, SUBJECT='dog', VERB='eats', OBJECT='food')) The dog eats the food