mardi 11 septembre 2018

Best way to check if condition or exception is thrown

Right now I have a function that excepts a string and is supposed to return none if the user either:

  • doesn't pass in a string OR
  • a specific exception is thrown when performing an operation on the argument

Here is how I am doing this:

def fnctn(num_str):
    if not isinstance(num_str, str):
        return None
    try:
        num = phonenumbers.parse(num_str, 'US')
    except phonenumbers.phonenumberutil.NumberParseException:
        return None
    ...

I am just wondering if there is a cleaner way of doing this. Like if I could check if the argument that was passed in was a string and check to see if the operation throws an exception or not on the same line?

Aucun commentaire:

Enregistrer un commentaire