Skip to content

Instantly share code, notes, and snippets.

@haydenbbickerton
Created August 25, 2017 22:14
Show Gist options
  • Save haydenbbickerton/ffbc48f9f821f16e7223892025fc5097 to your computer and use it in GitHub Desktop.
Save haydenbbickerton/ffbc48f9f821f16e7223892025fc5097 to your computer and use it in GitHub Desktop.
Safe string formatter
class SafeFormat(string.Formatter):
'''String formatting class that won't throw errors for usused/unfound args/kwargs.
Values that can't be retrieved are returned in their original '{keyname}' string
to allow for another round for .format()'ing
Example
-------
>>> safe_format = SafeFormat().format
>>> log_str = 'the {color} dog jumped over the {animal}'
# Pretend that it takes a lot of processing power to get the animal value,
# so we'll partially build it ahead of time and will add the animal later.
# This lets us log the string without having all the values.
>>> my_str = safe_format(log_str, color='brown') # 'the brown dog jumped over the {animal}'
# Later ...
>>> final_str = my_str.format(animal='cow') # 'the brown dog jumped over the cow'
'''
def get_value(self, key, args, kwds):
try:
return super(SafeFormat, self).get_value(key, args, kwds)
except (IndexError, KeyError):
return '{%s}' % key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment