Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if len is valid

Tags:

python

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

like image 615
DeadEli Avatar asked May 09 '14 14:05

DeadEli


People also ask

What is __ len __ in Python?

Python len() The len() function returns the number of items (length) in an object.

What is the output of Len 1 2 3 in python?

What is the output of len([1, 2, 3])? Ans: 3.

How do you check if a string is a certain length python?

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.

Does Len work for integer?

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.


2 Answers

You can do:

if hasattr(bar, '__len__'):     pass 

Alternatively, you can catch the TypeError.

like image 140
Nathaniel Flath Avatar answered Sep 19 '22 22:09

Nathaniel Flath


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 
like image 22
Martijn Pieters Avatar answered Sep 18 '22 22:09

Martijn Pieters