How to make a dictionary that returns key for keys missing from the dictionary instead of raising KeyError?

dicts have a __missing__ hook for this:

class smart_dict(dict):
    def __missing__(self, key):
        return key

Could simplify it as (since self is never used):

class smart_dict(dict):
    @staticmethod
    def __missing__(key):
        return key

Leave a Comment