typechecks: just say no! (was Re: Determining Types)

Emile van Sebille emile at fenx.com
Mon Sep 3 18:21:31 CEST 2001

"Alex Martelli" <aleax at aleax.it> wrote in message
news:9n077501por at enews1.newsguy.com...


> If I had to implement this in Python 2.1 or earlier,
> I'd use either variant of "it's easier to get
> forgiveness than permission", which after all IS
> the typical idiom to use where the unenlightened
> would typetest: i.e., either:
> def __getitem__(self, index):
>     try: return getattr(self, index)
>     except AttributeError:
>         fieldname=self.__fieldnames[index]
>         return fieldname, getattr(self, fieldname)
> or:
> def __getitem__(self, index):
>     try:
>         fieldname=self.__fieldnames[index]
>     except TypeError:
>         return getattr(self, index)
>     else:
>         return fieldname, getattr(self, fieldname)
> This would let client-code use any "index" that is
> string'ish enough to please getattr, or int'ish
> enough to please the [] indexing on __fieldnames
> (don't use double leading AND trailing __ for your
> own purposes, they're all "reserved to Python"!-).

Yes, but if you expect you're going to get a TypeError and program for that,
what's the difference if you do a type check first?


Emile van Sebille
emile at fenx.com

More information about the Python-list mailing list