Last active
November 10, 2016 13:04
-
-
Save ryllada/35b230f1b2e72b687883534ce66a8e44 to your computer and use it in GitHub Desktop.
This file contains 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
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