Reputation: 1053
I have a function
def foo(bar):
#do some things
len(bar)
If I call
foo(42)
it throws an exception of
TypeError: object of type 'int' has no len()
How do I check if the entered value can be used with len()?
Upvotes: 40
Views: 22445
Reputation: 1121744
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
Upvotes: 29
Reputation: 16015
You can do:
if hasattr(bar, '__len__'):
pass
Alternatively, you can catch the TypeError.
Upvotes: 53
Reputation: 473853
Since len()
calls __len__()
magic method under the hood, you can check if an object has __len__
method defined with the help of hasattr()
:
>>> def has_len(obj):
... return hasattr(obj, '__len__')
...
>>> has_len([1,2,3])
True
>>> has_len('test')
True
>>> has_len(1)
False
Upvotes: 8
Reputation: 32189
You can do it using try
and except
for best results:
def foo(bar):
#do some things
try:
print(len(bar))
except TypeError:
print('Input not compatible with len()')
Upvotes: 5