Feb-01-2020, 03:48 AM
Pages: 1 2
Feb-01-2020, 09:49 AM
>>> foo = type([]) >>> bar = [1,6,2,5,4,3] >>> hmm = isinstance(bar,foo) >>> hmm True
Feb-01-2020, 02:45 PM
my bad. i left out the most important part.
i have a function that may get an iterator of any kind. i want to test if it got an iterator.
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.
Feb-01-2020, 04:23 PM
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__') TrueSo you don't need foo.
Feb-01-2020, 07:59 PM
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()
.Feb-01-2020, 10:04 PM
You could test the existence of the
__next__
and __iter__
methods.Feb-03-2020, 06:10 PM
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__.
Feb-05-2020, 09:49 PM
from typing import Iterator, IterableI would suggest using Iterable unless you have a good reason to restrict to Iterators. But both work.
Feb-07-2020, 02:26 AM
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.
Feb-07-2020, 04:34 AM
Could run it trough
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
not saying this bad in all cases using
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