Skip to content

Instantly share code, notes, and snippets.

@sloanlance
Last active November 25, 2021 03:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sloanlance/fcb62476efa449d0c13f5c49cb0282d9 to your computer and use it in GitHub Desktop.
Save sloanlance/fcb62476efa449d0c13f5c49cb0282d9 to your computer and use it in GitHub Desktop.
`recursiveFormat()` – Recursively apply `string.format()` to all strings in a data structure.
def recursiveFormat(args, **kwargs):
"""
Recursively apply `string.format()` to all strings in a data structure.
This is intended to be used on a data structure that may contain
format strings just before it is passed to `json.dump()` or `dumps()`.
Ideally, I'd like to build this into a subclass of `json.JsonEncoder`,
but it's tricky to separate out string handling in that class. I'll
continue to think about it.
:param args: data structure; mostly dictionaries and lists
:param kwargs: values to be used in `string.format()`
:return: a new data structure with formatted strings
"""
if isinstance(args, Mapping):
return {key: recursive_format(value, **kwargs)
for (key, value) in args.items()}
elif isinstance(args, MutableSequence):
return [recursive_format(value, **kwargs)
for value in args]
else:
return args.format(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment