Handling typeerrors in Python

3168 views python
5

I am curious as to how often you should handle errors in Python. I have a function:

def char_to_lower(char):
    if ord('A') <= ord(char) <= ord('Z'):
        return chr(ord(char) + 32)
    else:
        return char

This function takes a char as input and returns it's associated lower case value. If I was to pass an int to this function I would get 'TypeError: ord() expected string of length 1, but int found'. My question is whether it considered proper/good practice to wrap this in a try/except block, catching a TypeError? Or whether it is acceptable to leave it as is and let the program fail with the built in Error mechanism.

answered question

You normally want to surface such an error. Errors are good things, they let you know something unexpected happened. If you know you may be passing an int to this function, and for some reason you are OK with that, go ahead and wrap the function call in a try-except and handle the error. But I would say it isn't good practice to put it inside, unless ytou want this function to handle both int and str objects for some reason (which would be code smell in my book). BTW, char isn't a data-type in python...

The fact that an int was passed to a function that is supposed to take a string, is a sign of a bigger problem. By masking the type error in the function, you let the bigger problem slip through the cracks. But, overall, the answer to this question is probably opinion-based.

1 Answer

4

def char_to_lower(char):
    if ord('A') <= char <= ord('Z'):
        return chr(char + 32) 
    else: 
        return char 

Do like this. Or you can easily do with chr(char).lower

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories