Module that provides the isiterable function to check if an object is iterable quickly for code in production.
Project description
isiterable
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.
Features of isiterable
Installation
pip install isiterable
Usage
from isiterable import isiterable
print(isiterable(57890)) # False
print(isiterable([1, "Hello!"])) # True
Using with classes
from 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
Other Examples
>>> from isiterable import isiterable
>>> isiterable(b"\x00\x01...")
True
>>> isiterable(callable)
False
>>> isiterable({"key1": True})
True
>>> isiterable([])
True
Alternatives to isiterable
If it doesn't match using isiterable
, there are some solutions where you know which is better.
try-iter
This involves calling __iter__
try:
iter(object)
except TypeError:
pass
has-iter
this will check if the object has the attribute __iter__
if hasattr(object, "__iter__"):
# ...
Benchmark
This small benchmark uses 3 code blocks:
Where
object
is 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.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for isiterable-1.0-cp310-cp310-linux_armv7l.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b318fc70e467ffabc4d230dfbeecde7457a62bb48dcc5aadb051b5bbc396e99a |
|
MD5 | 44b41d17f08fe7253c88346b5ca1fcf5 |
|
BLAKE2b-256 | 3382ec4ffdb830dd5d12baac24b3532faccd6692c12970668985c73f8fe5a19c |