To explain better, consider this simple type checker function:
from collections import Iterable
def typecheck(obj):
return not isinstance(obj, str) and isinstance(obj, Iterable)
If obj
is an iterable type other than str
, it returns True
. However, if obj
is a str
or a non-iterable type, it returns False
.
Is there any way to perform the type check more efficiently? I mean, it seems kinda redundant to check the type of obj
once to see if it is not a str
and then check it again to see if it is iterable.
I thought about listing every other iterable type besides str
like this:
return isinstance(obj, (list, tuple, dict,...))
But the problem is that that approach will miss any other iterable types that are not explicitly listed.
So...is there anything better or is the approach I gave in the function the most efficient?