user10019227
user10019227

Reputation: 117

Creating a function which return lengths

I want to create a function which returns the lengths of different input objects and returns -1 if there is not length.The expected output is below:

    my_dict = {'a': 23, 'b': 8}
    len_safe(my_dict)
2
    len_safe(7)
-1

I want to use exception handling but am confused as to how to start.

Upvotes: 0

Views: 143

Answers (2)

user3483203
user3483203

Reputation: 51165

You could use hasattr to check if an object has __len__ as an attribute, and return -1 otherwise:

def safe_len(o):
     return len(o) if hasattr(o, '__len__') else -1

In action:

>>> safe_len(7)
-1
>>> safe_len([1,2,3])
3

Upvotes: 1

zwer
zwer

Reputation: 25809

You can always capture a TypeError and return -1 if there is no len():

def len_safe(obj):
    try:
        return len(obj)
    except TypeError:
        return -1

I'm not sure of usability of such function, tho.

Upvotes: 2

Related Questions