Skip to content

Instantly share code, notes, and snippets.

@chriddyp
Created September 1, 2015 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriddyp/efb274b80be8daf29845 to your computer and use it in GitHub Desktop.
Save chriddyp/efb274b80be8daf29845 to your computer and use it in GitHub Desktop.
Subclass dictionaries with validation. A fun pattern for wrapping JSON APIs!
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