Created
September 1, 2015 22:04
-
-
Save chriddyp/efb274b80be8daf29845 to your computer and use it in GitHub Desktop.
Subclass dictionaries with validation. A fun pattern for wrapping JSON APIs!
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
def DictFactory(name, argnames, default_keys={}): | |
def __init__(self, **kwargs): | |
for key, value in kwargs.items(): | |
if key not in argnames: | |
raise TypeError("Argument %s not valid for %s" | |
% (key, self.__class__.__name__)) | |
kwargs.update(default_keys) | |
dict.__init__(self, **kwargs) | |
newclass = type(name, (dict,),{"__init__": __init__}) | |
return newclass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment