Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bulid type-safe assertive decorator #36

Open
boba-and-beer opened this issue Dec 7, 2020 · 0 comments
Open

Bulid type-safe assertive decorator #36

boba-and-beer opened this issue Dec 7, 2020 · 0 comments
Labels
enhancement New feature or request

Comments

@boba-and-beer
Copy link
Contributor

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 boba-and-beer added bug Something isn't working enhancement New feature or request and removed bug Something isn't working labels Dec 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant