Skip to content

Instantly share code, notes, and snippets.

@ryllada
Last active November 10, 2016 13:04
Show Gist options
  • Save ryllada/35b230f1b2e72b687883534ce66a8e44 to your computer and use it in GitHub Desktop.
Save ryllada/35b230f1b2e72b687883534ce66a8e44 to your computer and use it in GitHub Desktop.
import string
class BlankFormatter(string.Formatter):
""" With the use of this class, we avoid the KeyError in dictionary based
str.format when the key is missing.
"""
def __init__(self, default=''):
self.default = default
def get_value(self, key, args, kwargs):
if isinstance(key, (str, unicode, )):
return kwargs.get(key, self.default)
return string.Formatter.get_value(key, *args, **kwargs)
kwargs = {"name": "mark", "adj": "mad"}
fmt = BlankFormatter()
print fmt.format("My name is {name} and I'm really {adj}.", **kwargs)
# My name is mark and I'm really mad.
print fmt.format("My name is {name} and I'm really {adjective}.", **kwargs)
# My name is mark and I'm really .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment