Created
January 28, 2011 13:55
-
-
Save nfarring/800281 to your computer and use it in GitHub Desktop.
Python runtime type checking decorator function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
def typecheck(*args1,isclassmethod=False): | |
"""Python is a language with typed objects, but untyped references. This means that there is no compiler to help catch type errors at design time. This typecheck function acts as a function decorator so that you can declare the type of each function or method argument. At runtime, the types of these arguments will be checked against their declared types. | |
Example: | |
@typecheck(types.StringType, Decimal) | |
def my_function(s, d): | |
pass | |
If isclassmethod is True, then the first argument is skipped, since it is simply either self or cls and doesn't need to be typechecked. One important limitation of this decorator is that it cannot be used to typecheck an method argument that is of the same type as the method's class. The reason is that types do not exist until after Python has processed the entire class definition. And unfortunately, there is no way to forward-declare a class. For example, the following will not work: | |
class Foo(object): | |
@typecheck(Foo) | |
def hello(self, f): | |
print('hello: %s' % f) | |
Note that the Ruby language does not have this problem, or so I'm told.""" | |
def decorator(func): | |
@functools.wraps(func) | |
def wrapper(*args2, **keywords): | |
args = args2[1:] if isclassmethod else args2 | |
for (arg2,arg1) in zip(args,args1): | |
if not isinstance(arg2, arg1): | |
raise TypeError( | |
'expected type: %s, actual type: %s' % ( | |
arg1, type(arg2))) | |
return func(*args2, **keywords) | |
return wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment