I would like to define some generic decorators to check arguments before calling some functions.
Something like:
@checkArguments(types = ['int', 'float'])
def myFunction(thisVarIsAnInt, thisVarIsAFloat)
''' Here my code '''
pass
Side notes:
- Type checking is just here to show an example
- I'm using Python 2.7 but Python 3.0 whould be interesting too
I have a slightly improved version of @jbouwmans sollution, using python decorator module, which makes the decorator fully transparent and keeps not only signature but also docstrings in place and might be the most elegant way of using decorators
From the Decorators for Functions and Methods:
Usage:
I think the Python 3.5 answer to this question is beartype. As explained in this post it comes with handy features. Your code would then look like this
and results in
All of these posts seem out of date - pint now provides this functionality built in. See here. Copied here for posterity:
To enforce string arguments to a parser that would throw cryptic errors when provided with non-string input, I wrote the following, which tries to avoid allocation and function calls:
On Python 3.3, you can use function annotations and inspect:
If there is a validation error, prints:
If there is not a validation error, prints:
You can use a function rather than a lambda to get a name in the assertion failure.