Last active
March 11, 2019 10:52
-
-
Save mark-mishyn/0e4da583818077558e237dcbafd43437 to your computer and use it in GitHub Desktop.
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
class FormatDict(dict): | |
def __missing__(self, key): | |
return '{{{}}}'.format(key) | |
def format_string(string, context: dict) -> str: | |
""" | |
Format string without KeyError if key is not present in dict. | |
>>> format_string('Oh, hi {first_name} {last_name}', {'first_name': 'Mark'}) | |
'Oh, hi Mark {last_name}' | |
""" | |
return string.format_map(FormatDict(**context)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment