Type-checking module for Python

This module allows you to perform basic type-checking on the parameters passed to functions in your code. By applying the @typecheck decorator to a function, you can ensure that all the formal parameters are of the correct type.

Positional Parameters

The following code will raise a TypeCheckException to indicate that the value supplied for a is not the correct type.

@typecheck(int, str, str)
def my_func(a, b, c):
    pass

my_func('5', 'x', 'y')

When you supply a number of positional arguments to the @typecheck decorator, each call to the function will try to match user-supplied parameters with the types you have specified in the order that you list them.

Keyword Parameters

The following code will raise a TypeCheckException to indicate that the value supplied for a is not the correct type.

@typecheck(a=int, b=str, c=str)
def my_func(a=None, b=None, c=None):
    pass

my_func('5', 'x', 'y')

When you supply keyword arguments to the @typecheck decorator, each call to the function will try to match user-supplied parameters to the types you have specified based on the name of the keyword argument.

Note that you need to make sure the corresponding parameter to your function is a keyword parameter; the following code is valid but the a parameter will not be typechecked since it is a positional argument and not a keyword argument:

@typecheck(a=str)
def my_func(a):
    pass

Combining Parameter Types

You can combine positional and keyword parameters in both your function definition and in the call to the decorator:

@typecheck(int, b=str, c=str)
def my_func(a, b='', c=None):
    pass

my_func(5, c='y')

The code above will not generate a TypeCheckException since the b parameter's default value is of the correct type.

Using doctest

Because of the way that doctest gathers tests to run, it is not possible to run tests collected from typechecked functions "out-of-the-box". In order to enable support for this feature you need to add the following code to your project:

import typecheck.doctest_support

This line of code must appear in your project before any accesses to members of the doctest module.

Valid XHTML 1.0 Transitional