[Tutor] checksum of dictionary

Erik Price eprice@ptc.com
Thu Feb 13 14:19:06 2003


Gon=E7alo Rodrigues wrote:

> It depends. If the code is pythonically written then it just expects an
> onject with a dict-like interface/protocol/whatever you wanna call it (=
e.g.
> __getitem__, etc.).

[...]

> If the code does type checking (isinstance, etc.) then well, it does no=
t
> work. But in all honesty, how many times do you need a *real* dictionar=
y
> intead of something that just acts like one? Very few indeed.
>=20
> Check the cookbook, either the book or online, on
> Easier-to-ask-forgiveness-than-permission. It is a very pythonic way to=
 do
> interface-checking. You check that the object passed has the needed
> attributes, e.g.

[I didn't know that the cookbook was online.  Thanks, I will hunt it down=
.]

> 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.
>=20
> You can get more accurate checkings (checking signatures fir examples) =
using
> the inspect module.

Ah.  It becomes so much clearer to me now.  This is what people mean=20
when they say that it is okay in Python to throw exceptions even in=20
non-exceptional circumstances.

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

Thanks Gon=E7alo.  That helps me understand a lot.


Erik