How does __setitem__() work?

Janne Sinkkonen janne at nnets.fi
Mon Jun 19 18:14:27 EDT 2000


bob at slim.instantappointment.com (Bob Erb) writes:

> Given the following class definition,
> 
> class Test:
>     
>     def __setattr__(self, attribute, value):
>         print 'setting', attribute, 'to', value
>         self.__dict__[attribute] = value
>     
>     def __setitem__(self, index, value):
>         print 'setting index', index, 'to', value
>         ## THE_BLANK


> >>> t.list[0] = 7
> 
> That doesn't happen; when does __setitem__ get
> called?

When you write t[0]=7. 

> My second question is, to pass the assignment in
> __setitem__ through, what code goes in 'THE_BLANK'
> above?

Something like self.list[index]=value.

> (What I'm trying to do is ensure that the value of
> a variable is a certain type. For instance, I want
> to disallow assignment of a string value to an
> integer variable. Is this anti-Python?)

No, but IMHO you'd be better off by writing a method called
Test.set<List>Item(index,value), where <List> is replaced by something
descriptive, or the whole method name is replaced by something more
oriented to your problem domain. If you also write an access method
(Test.getListItem() or some such) for your list, then the
implementation is completely hidden behind a well-defined interface.

To get the type checking working automagically probably requires (or
would be clearest if written as) two classes, one for the
functionality of Test, and one for the functionality of your
type-checking list. But all this is too much coding overhead just to
make the class interface "fancy". Unless, of course, you intend to use
your new list type very very often.

You should also think of whose stupidity you're trying protect your
class from. If the answer is yourself, consider skipping the type
checks and instead documenting the class interface carefully. 

Also make sure you're aware of 'assert'.

-- 
Janne



More information about the Python-list mailing list