2

Basically the argument that foo() expects should be passed as int, but there is a possibility that someone will pass it as str (which is also valid if str can be converted to int). This is what I came up with:

def foo(input_argument):
    func_name = 'foo'

    if type(input_argument) is not int or type(input_argument) is not str:
        print(
            '%s: "input_argument" expects int/str, not %s' % (
                func_name,
                type(input_argument)
            )
        )
        return None
    try:
        input_argument= int(input_argument)
    except:
        print(
            '%s: "input_argument" expects number in str/int format' % func_name
        )
        return None

Is there something that is built-in which could simplify this in a more pythonic way?

Edit: boolean type should be treated as invalid

Sir DrinksCoffeeALot
  • 593
  • 2
  • 11
  • 20

3 Answers3

1

You could eventually use some data validation library, like Cerberus, but like jonsharpe said in a comment, the common way is to let python handle the error by simply try to convert the input into an integer.

Just do:

def foo(input_argument):
    input_argument= int(input_argument)
    # ... your method

Take a look there for more on the subject: https://stackoverflow.com/a/154156/4279120

olinox14
  • 6,177
  • 2
  • 22
  • 39
  • Our custom environment for running these scripts doesn't really support duck typing, it breaks if exception occurs so we have to handle these exceptions by ourselves, but I do get the point! – Sir DrinksCoffeeALot Aug 30 '19 at 08:21
1

You can use type hints to get IDE support for types (the IDE will tell you if you are passing a wrong type)... anyway nothing will prevent to pass a wrong type at runtime, so you can check it as in the following snippet and raise a ValueError if the received object is not the expected one:

def foo(input: Union[int, str]):
    if not isinstance(input, (int, str)):
        raise ValueError(f'Invalid input, expected int or str, got: "{type(input)}"')

    # ...implementation
daveoncode
  • 18,900
  • 15
  • 104
  • 159
  • The post is tagged with python 2.7; the syntax you use here is Python 3 only. Mypy and PyCharm support hints in comments, use those. – Martijn Pieters Aug 30 '19 at 08:59
0

I think you're overcomplicating things

import sys

def foo(input_argument):
    try:
        input_argument = int(input_argument)
    except Exception:
        print('Unexpected error occured: %s' % sys.exc_info()[1])

or with better error handling

def foo(input_argument):
    try:
        input_argument = int(input_argument)
    except ValueError:
        print('That is not a number, but a string')
    except TypeError:
        print('That is not a number')
Tim Stack
  • 3,209
  • 3
  • 18
  • 39