[Tutor] Re: __setattr__ for dictionary???

Emile van Sebille emile@fenx.com
Sat Nov 9 18:57:02 2002


Runsun Pan:
> hi i'm trying to use the __setattr__ to do some
> data check before they are stored into my class.
> I've learned :
>
> def __setattr__(self, nsmr, value)
>
> how do i use that to do a data check on the entry of
> a dictionary item?
>
> For example, a dict:
>
> peoplename={'last':'Lee', 'first':'john'}
>
> how do i use the __setattr__ for it ?
>

I'm not quite clear on your intent, but maybe this fits.  Instead of
setattr, I use setitem and both validate and clean up the value:

>>> class Sample(dict):
...     def __init__(self, validatefunc, cleanupfunc):
...         self.isgood = validatefunc
...         self.clean = cleanupfunc
...     def __setitem__(self, key, value):
...         if self.isgood(value):
...             dict.__setitem__(self, key, value.capitalize())
...         else:
...             raise ValueError, 'Invalid Length'
...
>>> def lengthtest(value):
...     return 3<=len(value)<=10
...
>>> def capitalize(value):
...     return value.capitalize()
...
>>> a = Sample(lengthtest, capitalize)
>>> a['last'] = 'test'
>>>
>>> print a['last']
Test
>>> a['first']='ab'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 9, in __setitem__
ValueError: Invalid Length
>>> a['first']='abe'
>>> a
{'last': 'Test', 'first': 'Abe'}


HTH,


--

Emile van Sebille
emile@fenx.com

---------