isiterable is a Python module that provides the isiterable function, which acts as an object checker to know if it is iterable or not. It does not call the function and also has no undesirable performance numbers.
pip install --upgrade isiterablefrom isiterable import isiterable
print(isiterable(57890)) # False
print(isiterable([1, "Hello!"])) # Truefrom isiterable import isiterable
class NoIters:
def __init__(self, *args):
self.args = args
def __iter__(self):
# isiterable will return False, Must be a generator :/
return self.args
class YesIters:
def __init__(self, *args):
self.args = args
def __iter__(self):
# Works!
for arg in args:
yield arg
x = YesIters((1, 2))
res = isiterable(x)
print(res) # True
x = NoIters("Hello!")
res = isiterable(x)
print(res) # False>>> from isiterable import isiterable
>>> isiterable(b"\x00\x01...")
True
>>> isiterable(callable)
False
>>> isiterable({"key1": True})
True
>>> isiterable([])
TrueIf it doesn't match using isiterable, there are some solutions where you know which is better.
This involves calling __iter__
try:
iter(object)
except TypeError:
passthis will check if the object has the attribute __iter__
if hasattr(object, "__iter__"):
# ...This small benchmark uses 3 code blocks:
Where
objectis the argument to pass
Running benchmark.py will give results similar to this
Running 1,000,000 times each block of code...
Results of isiterable: 0.381
Results of hasiter : 0.777
Results of tryiter : 5.689
The best result is isiterable while tryiter having the worst result.