On 7/21/06, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> Since builtin dicts and dict subclasses will already be iterable, the
> mappings in question would be from user-defined classes with lookup
> behavior and but not providing an iterator:
>
>    class C:
>         '''This could be either a mapping or sequence
>            so it would be foolish to wrap it with a SeqIter'''
>         def __getitem__(self, k):
>              return f(k)
>         def __len__(self):
>              return L
>
> So, by default, iter(C()) will now raise a TypeError and provide earlier
> detection of an error rather than waiting for a potential KeyError
> during iteration.  And even if C was intended to be a sequence,
> list(C()) would raise a TypeError rather than risk a KeyError if C
> turned-out to be a mapping.
>
> Since all of the builtin sequences will already define __iter__, they
> are unaffected by this change.  What is left are user-defined sequence
> classes or extensions with __getitem__ but not __iter__.  To make those
> iterable, the user would need to either modify the class (if possible)
> or provide a SeqIte- like wrapper:
>
>     def SeqIter(s):
>         try:
>             for i in itertools.count():
>                  yield s[i]
>         except IndexError:
>             return
>
>    for elem in SeqIter(s): ...    # be explicit about looping over a
> generic sequence
>
>    L = list(SeqIter(s))             # explicit wrapper to avoid a
> TypeError for generic sequences
>
>
> Does that correctly recap your proposal, its motivitations, and its
> implications?

Yes. Though I would strongly recommend that all user-defined sequences
should provide an explicit __iter__(). It's only a few lines (and of
course often can be done faster using knowledge of the
implementation):

def __iter__(self):
  for i in itertools.count():
    yield self[i]


-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)
_______________________________________________
Python-3000 mailing list
Python-3000@python.org
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe: 
http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com

Reply via email to