Skip to content

Instantly share code, notes, and snippets.

@mark-mishyn
Last active March 11, 2019 10:52
Show Gist options
  • Save mark-mishyn/0e4da583818077558e237dcbafd43437 to your computer and use it in GitHub Desktop.
Save mark-mishyn/0e4da583818077558e237dcbafd43437 to your computer and use it in GitHub Desktop.
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