How to check if len is valid

Question:

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()?

Asked By: DeadEli

||

Answers:

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()')
Answered By: sshashank124

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
Answered By: Martijn Pieters

You can do:

if hasattr(bar, '__len__'):
    pass

Alternatively, you can catch the TypeError.

Answered By: Nathaniel Flath

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
Answered By: alecxe
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.