typechecks: just say no! (was Re: Determining Types)
David C. Ullrich
ullrich at math.okstate.edu
Tue Sep 4 10:28:11 EDT 2001
On 3 Sep 2001 15:27:09 GMT, Marcin 'Qrczak' Kowalczyk
<qrczak at knm.org.pl> wrote:
>Mon, 03 Sep 2001 14:31:04 GMT, David C. Ullrich <ullrich at math.okstate.edu> pisze:
>
>> 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.
>
>Newer versions of Python allow to define how the object is iterated over
>independently of indexing.
So I hear. At some point I have to give in and get a newer
version... thanks.
>Define method __iter__ which returns an iterator (an object which
>keeps a state, whose next method returns the next object or raises
>StopIteration, and whose __iter__ method returns self).
>
>In this case the iterator can be defined thus (untested):
>
> def __iter__(self):
> for name in self.__fieldnames__:
> yield (name, getattr(self, name))
>
>You will need
> from __future__ import generators
>at the top of the module.
>
>BTW, iteration over a dictionary now yields its keys. You may consider
>conforming to this convention:
>
> def __iter__(self):
> return iter(self.__fieldnames__)
>
>--
> __("< Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
> \__/
> ^^ SYGNATURA ZASTÊPCZA
>QRCZAK
David C. Ullrich
More information about the Python-list
mailing list