Python Forum

Full Version: type of result of iter()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
what value for foo will cause isinstance to return True?
    foo = ???
    bar = [1,6,2,5,4,3]
    hmm = isinstance(bar,foo)
>>> foo = type([])
>>> bar = [1,6,2,5,4,3]
>>> hmm = isinstance(bar,foo)
>>> hmm
True
my bad. i left out the most important part.

foo = ???
bar = [1,6,2,5,4,3]
bar = iter(bar)
hmm = isinstance(bar,foo)
and i don't want to get this by calling type()

i have a function that may get an iterator of any kind. i want to test if it got an iterator.
Very interesting, but I think I do no understand your logic. If you want to check whether an object is iterable, you may use:
>>> hasattr(bar, '__iter__')
True
So you don't need foo.
i'm looking for the difference between just iterable (a list is iterable) and an iterator, such as (but not limited to) something returned from iter().
You could test the existence of the __next__ and __iter__ methods.
a list has __iter__ but not __next__. so it looks like __next__ is the thing to check. i was thinking of checking for __len__. iterators don't have __len__.
from typing import Iterator, Iterable
I would suggest using Iterable unless you have a good reason to restrict to Iterators. But both work.
i usually have issues like this with functions that i expect to be made public. i like to deal with variations of user input. for example, a function to work with strings, i like to also support bytes. but in many cases i have to do things that require different handling. i've encountered this with iterators in recent weeks.
Could run it trough next(),and catch the in error in try:except.
Then it follow EAFP(easier to ask for forgiveness than permission).
This style is often look up upon as better than LBYL(Look Before You Leap).
Example using isinstance, hasattr or eg os.path.isfile(fname) is LBYL,
not saying this bad in all cases using isfile or isinstance can be more convenient than write a try:except for it.
class NotIterator(Exception):
    """Exception raised when not an iterator"""
    pass

def iterator_check(arg):
    try:
        n = next(arg)
        print(n)
    except TypeError:
        raise NotIterator("Need iterator as input")

if __name__ == '__main__':
    lst = [1,6,2,5,4,3]
    lst_iter = iter(lst)
    # Generator a good wav to make a iterator
    numbers = [2, 4, 12, 32, 40, 67]
    squares = (n**2 for n in numbers)
    iterator_check(lst)
Error:
During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<module1>", line 18, in <module> File "<module1>", line 10, in iterator_check NotIterator: Need iterator as input
Pages: 1 2