Search code examples
pythonpython-3.xpython-decorators

How to use function decorators to check type of function?


How would I use a function decorator to check the argument of another function? I'm trying to wrap my head around function decorators but it's super confusing.

Ideally I would like it work like this, you pass in an int and a function below and the function works else you get a type error.

@check(int)
def printer(arg):
    print(arg)
>>> printer(5)
5

This is what I tried but it doesn't work.

def check(typ):

    def validate(args):
        if type(args) == typ:
           return validate(args)
        else:
           raise TypeError

    return validate

Any advice or guidance would be appreciated, been really trying to wrap my head around decorators.


Solution

  • check(int) still has to return a function.

    def check(typ):
        def checker(f):
            def checked_func(arg):
                if isinstance(arg, typ):
                    return f(arg)
                else:
                    raise TypeError
            return checked_func
        return checker
    

    Now, _ is the actual decorator returned by check, and _ takes the original function and wraps it in another function which checks the type of the argument, and either returns the result of the original function applied to the argument, or raises a TypeError.

    It might be easier to follow if we break it into more pieces.

    int_checker = check(int)
    
    @int_checker
    def printer(arg):
        print(arg)