-
-
Save lsloan/e47ad220846e0e9dc0a561fb3135933e to your computer and use it in GitHub Desktop.
`recursiveFormat()` – Recursively apply `string.format()` to all strings in a data structure.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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