Recently I've been doing a lot of music based programming, and as such find myself doing this kind of thing a lot to deal with missing metadata in some songs:
default = {'title': 'Unknown title', 'artist': 'unknown Artist'}
default.update(song)
print '{title} - {artist}'.format(**default)
Is there a cleaner way to do this? I tried overriding __missing__ like so but missing keys still throw a KeyError:
class Song(dict):
# dictionary with some nice stuff to make it nicer
def __missing__(self, key):
return 'Unknown {key}'.format(key = key)
Edit: Sorry I should have been clearer, basically the following must work.
s = Song()
print '{notAKey}'.format(s)
A couple of people have pointed out that the **s are not necessary.
Edit 2: I've "solved" my problem, at least to my satisfaction. It's debatable whether or not this is cleaner, but it works for me.
from string import Formatter
class DefaultFormatter(Formatter):
def get_value(self, key, args, kwargs):
# Try standard formatting, then return 'unknown key'
try:
return Formatter.get_value(self, key, args, kwargs)
except KeyError:
return kwargs.get(key, 'Unknown {0}'.format(key))
class Song(dict):
def format(self, formatString):
# Convenience method, create a DefaultFormatter and use it
f = DefaultFormatter()
return f.format(formatString, **self)
So the following will return 'Unknown notAKey'
k = Song()
print k.format('{notAKey}')