Created
August 25, 2017 22:14
-
-
Save haydenbbickerton/ffbc48f9f821f16e7223892025fc5097 to your computer and use it in GitHub Desktop.
Safe string formatter
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 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