How to check if len is valid
You can test if the object is Sized
:
import collections.abc
if isinstance(bar, collections.abc.Sized):
The isinstance()
test is true if all abstract methods of Sized
are implemented; in this case that's just __len__
.
Personally, I'd just catch the exception instead:
try:
foo(42)
except TypeError:
pass # oops, no length
You can do:
if hasattr(bar, '__len__'):
pass
Alternatively, you can catch the TypeError.