I recently did a lot of music programming, and as such, I do such things to deal with the 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 this, but missing keys still throw a KeyError:
class Song(dict):
def __missing__(self, key):
return 'Unknown {key}'.format(key = key)
Edit: Sorry, I should have been more clear, basically this should work.
s = Song()
print '{notAKey}'.format(s)
Several people indicated that ** are not needed.
Edit 2: I “solved” my problem, at least until I was satisfied. Whether it is debatable or not cleaner, but it works for me.
from string import Formatter
class DefaultFormatter(Formatter):
def get_value(self, key, args, kwargs):
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):
f = DefaultFormatter()
return f.format(formatString, **self)
So the following will be returned "Unknown notAKey"
k = Song()
print k.format('{notAKey}')