Dictionary from list?

Tim Peters tim.one at home.com
Mon Oct 29 00:33:50 EST 2001


[Terry Reedy]
> ...
> To me, 'exactly 2' implies that dictionary() calls pair.next() a third
> time and objects if it succeeds (as I believe it should, see below).
> Presently true?

It means that if len(list(iterable_object)) != 2, you get an exception about
the length, while if len(list(iterable_object)) == 2 you do not.  Exactly
how "exactly two" is determined is not defined, because over-defining errot
cases constrains the implementation in pointless ways.  Tickling pair.next()
a third time is one possible implementation.  But, for example, if the
iterable object happens to be a tuple or list, it would be a *silly*
implementation to build an iterator at all, since tuples and lists store
their sizes explicitly, and "exactly 2" is directly determinable for them
(FYI, the current implementation does avoid building iterators for tuples
and lists; maybe it won't be the time 2.2final is released, but "exactly 2"
will remain the rule).

...
>>     class AddressBookEntry:
>>         # with .firstname, .lastname attributes
>>         ...
>>         def __iter__(self):
>>             return iter((self.firstname, self.lastname))
>>
>> A sequence of AddressBookEntry instances is OK to pass to
>> dictionary(), despite that an AddressBookEntry defines neither __len__
>> nor __getitem__.  A generator yielding instances of AddressBookEntry is
>> also fine; etc.

> Here's the 'below' twice referred to above:  Would AddressBookEntry
> instances still be OK if the last line were, for instance, changed to
>
>     return iter((self.firstname, self.lastname, self.address))

No; in that case you'd get a ValueError exception complaining that the
number of elements produced by the iterator isn't exactly 2.  Ditto if
changed to

    return iter([self.firstname])

etc.

> My point about a length of exactly two is a) the observation that
> silently ignoring items beyond two is not consistent with the
> processing of literals ('d={1:2:3}', for example, is a SyntaxError)
> and b) my feeling that doing so would as often be wrong, creating a
> silent bug, as right.

Exactly so.

> ...
> Glad we agree ;<)

Indeed, it appears unstoppable <wink>.





More information about the Python-list mailing list