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

David C. Ullrich ullrich at math.okstate.edu
Mon Sep 3 10:31:04 EDT 2001


On Mon, 3 Sep 2001 13:02:54 +0200, "Alex Martelli" <aleax at aleax.it>
wrote:

>"Adonis Vargas" <deltapigz at telocity.com> wrote in message
>news:fe9k7.1835$ix.446807 at newsrump.sjc.telocity.net...
>> how am i able to determine types of variables? i have come up with the
>
>Be aware that, MOST times you THINK you need to typecheck, you
>really *don't*.  Type-checks break the wonderful signature based
>polymorphism that is the key to so much of Python's power and
>simplicity.  Check out the Cookbook recipe:
>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291
>for a way to avoid type-checking (in favour of signature
>checking) even when you might think it's indispensable.

Just the other day I did something that involves type checking.
I felt guilty about it, but it gives me what I want. How do
I do the following without type-checking? (Or how do I do
something other than the following that retains the keenness
of it?)

I have records. Rec has (almost) no user-defined attributes except
for __getitem__; fields are assigned dynamically from
field names in the database, using settattr() when a record
is read. So I can use rec.thisfield and rec.thatfield even
though the Rec class doesn't know about "thisfield" and
"thatfield", keen.

But in other places it's good to be able to refer to
fields with non-literal names, so I add a __getitem__
so that rec['thisfield'] returns rec.thisfield. 
(Actually the main reason I want this is so that I
can use a Rec as a mapping in a string format thing:

'Your name is %(Name)s' % rec)

In yet other places I want to iterate over the fields 
of a record, as in

for key, value in rec:

So in __getitem__ I check the type of index, returning
getattr(self, index) if index is a string and saying

fieldname=self.__fieldnames__[index]
return (fieldname, getattr(self, fieldname))

if index is an integer.

Seems utterly keen to be able to use them as both 
lists and as mappings, as needed.



David C. Ullrich



More information about the Python-list mailing list