Scott Chapman
scott_list at mischko.com
Thu Oct 5 16:53:53 EDT 2006
Here's a more robust version: class FormDict(dict): '''This is a special dict that checks items as they are assigned. It would be useful for web form submissions, etc. At dict creation, errors are accumulated, if any, and sent back as a group.''' def __init__(self,**dictparms): # If there are defaults, assign them first: # self.__setitem__(key, value) # if you need to bypass your own setitem checking: # super(FormDict, self).__setitem__(key, mvalue) # Set the valid keys here: self.__valid_keys = ('id',) errors = [] for key in dictparms: try: self.__setitem__(key, dictparms[key]) except RuntimeError,e: errors.append(str(e)) if errors: raise RuntimeError(errors) def __setitem__(self, key, value): if not key in self.__valid_keys: raise RuntimeError, "Invalid Key: %s" % key # Put your own checks here. # If you don't create a check for a given valid key, anything will be acceptable. if key =='id': try: mvalue = int(value) except: raise RuntimeError, "Invalid ID: %s" % mvalue if mvalue <= 0: raise RuntimeError, "Invalid ID: %s" % mvalue super(FormDict, self).__setitem__(key, mvalue) elif key == 'foo': super(FormDict, self).__setitem__(key, mvalue) elif key in self.__valid_keys: super(FormDict, self).__setitem__(key, mvalue) else: raise RuntimeError, "Invalid Key" if __name__ == '__main__': try: md = FormDict(id=1,name='bill',address='123 any street') except RuntimeError, e: error_list = list(e[0]) for error in error_list: print error md = FormDict(id=1)
|