[Tutor] use of the newer dict types
Dave Angel
davea at davea.name
Fri Jul 26 03:38:08 CEST 2013
On 07/25/2013 09:27 PM, eryksun wrote:
> On Thu, Jul 25, 2013 at 7:51 PM, Dave Angel <davea at davea.name> wrote:
>>
>> And it's apparently safe to change the dictionary after creating the view,
>> UNTIL the iterator is created.
>
> Notice the error the iterator raised in my example was just about the
> dict changing size. If the dict changes between steps while remaining
> the same size, the iterator doesn't have a clue:
So in other words, it's unsafe to change the dictionary after creating
the iterator, but it won't necessarily cause an exception; it might
happen to work, or it might just get weird results.
>
> >>> d = dict.fromkeys('abcdef')
> >>> d2 = dict.fromkeys('ghijkl')
>
> >>> keys = d.keys()
> >>> it = iter(keys)
> >>> next(it)
> 'f'
> >>> next(it)
> 'e'
>
> >>> d.clear()
> >>> d.update(d2)
> >>> list(it)
> ['l', 'k', 'j', 'i', 'h']
>
> 'g' got skipped. The result here depends on the iterator's current
> index into the hash table and the positions that the updated values
> hash to.
>
>> I still don't see the advantage. Isn't the iterator going to be as big as
>> the list would have been, and take just as long to build?
>
> It already has the hash table. It just has to iterate it looking for
> non-NULL values, and keep track of the previous index between calls to
> __next__().
In other words, no? The iterator assumes the dict is no longer going to
change once the iterator is created, so it can just store iteration state.
>
> Another bit of state the iterator maintains is a length hint, which
> helps to optimize memory allocation when using the iterator to create
> a new sequence:
>
> >>> d = dict.fromkeys('abcdef')
> >>> it = iter(d)
> >>> it.__length_hint__()
> 6
> >>> next(it)
> 'f'
> >>> it.__length_hint__()
> 5
It'd sure be nice if the library reference actually specified the
external behavior, though I have no problem with it omitting things like
__length_hint__. Those are implementation details.
--
DaveA
More information about the Tutor
mailing list