diff --git a/pandera/pandera.py b/pandera/pandera.py index f4c9a6811..34ae9ef21 100644 --- a/pandera/pandera.py +++ b/pandera/pandera.py @@ -999,7 +999,21 @@ def check_input( def _wrapper(fn, instance, args, kwargs): args = list(args) if isinstance(obj_getter, int): - args[obj_getter] = schema.validate(args[obj_getter]) + try: + args[obj_getter] = schema.validate(args[obj_getter]) + except IndexError as e: + raise SchemaError( + "error in check_input decorator of function '%s': the " + "index '%s' was supplied to the check but this " + "function accepts '%s' arguments, so the maximum " + "index is '%s'. The full error is: '%s'" % + (fn.__name__, + obj_getter, + len(_get_fn_argnames(fn)), + max(0, len(_get_fn_argnames(fn))-1), + e + ) + ) elif isinstance(obj_getter, str): if obj_getter in kwargs: kwargs[obj_getter] = schema.validate(kwargs[obj_getter]) diff --git a/tests/test_pandera.py b/tests/test_pandera.py index d5c943d06..9f5ca5331 100644 --- a/tests/test_pandera.py +++ b/tests/test_pandera.py @@ -230,6 +230,9 @@ def test_func4(x, dataframe): def test_check_function_decorator_errors(): + """Test that the check_input and check_output decorators error properly.""" + # case 1: checks that the input and output decorators error when different + # types are passed in and out @check_input(DataFrameSchema({"column1": Column(Int)})) @check_output(DataFrameSchema({"column2": Column(Float)})) def test_func(df): @@ -245,6 +248,19 @@ def test_func(df): match=r"^error in check_output decorator of function"): test_func(pd.DataFrame({"column1": [1, 2, 3]})) + # case 2: check that if the input decorator refers to an index that's not + # in the function signature, it will fail in a way that's easy to interpret + @check_input(DataFrameSchema({"column1": Column(Int)}), 1) + def test_incorrect_check_input_index(df): + return df + + with pytest.raises( + SchemaError, + match=r"^error in check_input decorator of function" + ): + test_incorrect_check_input_index(pd.DataFrame({"column1": [1, 2, 3]}) + ) + def test_check_function_decorator_transform(): """Test that transformer argument is in effect in check_input decorator."""