#7398: Added is_iterator method and fixes sage to use it.
---------------------------------+------------------------------------------
Reporter: nthiery | Owner: hivert
Type: enhancement | Status: new
Priority: major | Milestone:
Component: misc | Keywords: iterators
Work_issues: | Author: Florent Hivert
Reviewer: Nicolas M. ThiƩry | Merged:
---------------------------------+------------------------------------------
Description changed by hivert:
Old description:
> The following mantra occurs at three places in Sage's code to test
> whether v is an iterator:
>
> if hasattr(v, 'next'):
>
> This patches replaces them with:
>
> if hasattr(v, '__iter__')
>
> which is safer (some sage objects have a next method without being
> iterable, or with a different semantic)
>
> if not just, when appropriate:
>
> v = iter(v)
New description:
The following mantra occurs at three places in Sage's code to test whether
v is an iterator:
{{{
if hasattr(v, 'next'):
}}}
This is not quite correct since some sage objects have a next method
without being iterable, or with a different semantic.
Let me quote python's doc:
> The iterator objects themselves are required to support the following
two methods, which together form the iterator protocol:
> iterator.__iter__()::
>
Return the iterator object itself. This is required to allow both
containers and iterators to be used with the for and in statements. This
method corresponds to the tp_iter slot of the type structure for Python
objects in the Python/C API.
> iterator.next()::
>
Return the next item from the container. If there are no further
items, raise the StopIteration exception. This method corresponds to the
tp_iternext slot of the type structure for Python objects in the Python/C
API.
Therefore here is the good way to test if an element is an iterator:
{{{
try:
return it is iter(it)
except:
return False
}}}
Note: it is not sufficient to check for the existence of the methods since
some sage object implement {{{__iter__}}} to raise a {{{NotImplemented}}}
exception !
Florent
--
--
Ticket URL: <http://trac.sagemath.org/sage_trac/ticket/7398#comment:1>
Sage <http://www.sagemath.org>
Sage: Creating a Viable Open Source Alternative to Magma, Maple, Mathematica,
and MATLAB
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sage-trac" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/sage-trac?hl=en
-~----------~----~----~----~------~----~------~--~---