[Tutor] checksum of dictionary

Gonçalo Rodrigues op73418@mail.telepac.pt
Thu Feb 13 15:45:02 2003


----- Original Message -----
From: "Erik Price" <eprice@ptc.com>
To: "Gonçalo Rodrigues" <op73418@mail.telepac.pt>
Cc: <tutor@python.org>
Sent: Thursday, February 13, 2003 7:14 PM
Subject: Re: [Tutor] checksum of dictionary


[snip]
>
> So this is the Pythonic approach?  I much like it.  It lets you use any
> object as long as it implements the necessary method.  Or rather, it
> lets you use any object as long as it doesn't raise a TypeError.
>

The important thing is that the code raises an exception. It's a way of
saying: I can't work with you. I chose to raise TypeError because according
to the docs:

TypeError:
Raised when a built-in operation or function is applied to an object of
inappropriate type. The associated value is a string giving details about
the type mismatch.

But notice that even this type of initial checking may not be needed. For
example

(A)
def bogusfunction(obj):
    #This raises an exception if obj has no __getitem__.
    bogusvar = obj[0]

The advantage of doing an intial check like:

(B)
> def bogusfunction(obj):
>     #Are you sufficiently dict-like?
>     try:
>         obj.__getitem__
>     except AttributeError:
>         raise TypeError("Hey buster, I can't work with you!")
>     #Proceed with code.

is that of you have a lot of operations, in the (A) case some could succed
and some fail, partially altering the object and possibly leaving it in an
"inconsistent state". With (B) you make some initial checks and while things
can still go wrong it much less likely so.

An this leads me to the one point that I forgot to mention: to produce
robust code you have to test it. Check the unittest module.

All the best,
G. Rodrigues