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()?
Python len() The len() function returns the number of items (length) in an object.
What is the output of len([1, 2, 3])? Ans: 3.
You can use the len() to get the length of the given string, array, list, tuple, dictionary, etc. Value: the given value you want the length of. Return value a return an integer value i.e. the length of the given string, or array, or list, or collections.
Nope, you can't use len() on an integer, Change it to a string by adding quotation marks a = '12665' and len() will work fine.
You can do:
if hasattr(bar, '__len__'): pass
Alternatively, you can catch the TypeError.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With