[Tutor] __setitem__

Michael Janssen Janssen at rz.uni-frankfurt.de
Fri Feb 27 08:31:20 EST 2004

On Thu, 26 Feb 2004, Christopher Spears wrote:

> What does __setitem__ do?  From reading the docs, I
> think it has something to do with setting values in a
> class.

Hi Christopher,

as Gregor stated: it's more for setting values on an object. A class is
what a programmer uses to create objects.

The point of my post is to name the tool that helps to regocnize what
"__setitem__ or all those __methods__ of an object" might be:

>>> my_object = {} # creating a new dictionary
>>> dir(my_object) # looking "into" this object
[snip: complete list of methods that a python dicts have. Try it out]

Here you will see, that a dictionary has several special methods like
__setitem__ and several not-that-special methods like keys or get .

The special methods are what do the dictionaries functionality, when you
work "via syntax" on the dictionary:

>>> my_object["no such key"]     # uses __getitem__ internally
>>> my_object["a new key"] = 0   # uses __setitem__
>>> if "a new key" in my_object: # __contains__ (? not sure)

The other normal methods are just used as is: my_object.keys()

You can also do:
>>> my_object.__getitem__("no such keys")
>>> my_object.__setitem__("a new key")

and so on. This way you name the special methods directly. Effect is
the same than using syntax stuff.

What UserDict basically does is to create an internal real dictionary
("real" in contrast to "User"-Dict) within __init__:

    def __init__(self, dict=None):
        self.data = {}
        if dict is not None: self.update(dict)

then UserDict maps all special methods and normal methods to the ones of
the internally used dict. E.G. __setitem__ :

    def __setitem__(self, key, item):
         self.data[key] = item

here UserDict.__setitems__ gets translated/mapped via syntax into
__setintem__ of the internally used dictionary self.data . And the same
for all other methods.

What's the good of UserDict? It's the simplest way to override some
methods without the need of reimplementing all other method, because
UserDict has allready done it for you.

"overriding" can be done by Subclassing:

class My_UserDict(UserDict.UserDict):
     def __setitem__(self, key, item):
         print "you've asked me to insert %s in key: %s" \
               % (item, key)
         print "since I don't do it, this is just for"
         print "educational purpose"

my_dict = My_UserDict()
my_dict["set a key, try to..."] = 0 # won't work but print a message
my_dict.keys()  # this and all other methods works as normal

# try also "dir(my_dict)": no visible difference to dir({})

So, I hope it's getting clearer to everyone what "__special_methods__"
means and how to override them. Now you should have a better chance to
find the solution for ordered keys :-)


More information about the Tutor mailing list