vectorai icon indicating copy to clipboard operation
vectorai copied to clipboard

Bulid type-safe assertive decorator

Open boba-and-beer opened this issue 5 years ago • 0 comments

With Python's type-safety is difficult but it can be implemented through smart use of Python decorators. An interesting example can be seen below:

import itertools as it

@parametrized
def types(f, *types):
    def rep(*args):
        for a, t, n in zip(args, types, it.count()):
            if type(a) is not t:
                raise TypeError('Value %d has not type %s. %s instead' %
                    (n, t, type(a))
                )
        return f(*args)
    return rep

@types(str, int)  # arg1 is str, arg2 is int
def string_multiply(text, times):
    return text * times

print(string_multiply('hello', 3))    # Prints hellohellohello
print(string_multiply(3, 3))          # Fails miserably with TypeError

# From: https://stackoverflow.com/questions/5929107/decorators-with-parameters

boba-and-beer avatar Dec 07 '20 01:12 boba-and-beer