taurus.core.util.decorator.typecheck

One of three degrees of enforcement may be specified by passing the ‘debug’ keyword argument to the decorator:

  • 0 – NONE: No type-checking. Decorators disabled.

  • 1 – MEDIUM: Print warning message to stderr. (Default)

  • 2 – STRONG: Raise TypeError with message.

If ‘debug’ is not passed to the decorator, the default level is used.

Example usage:

>>> NONE, MEDIUM, STRONG = 0, 1, 2
>>>
>>> @accepts(int, int, int)
... @returns(float)
... def average(x, y, z):
...     return (x + y + z) / 2
...
>>> average(5.5, 10, 15.0)
TypeWarning:  'average' method accepts (int, int, int), but was given
(float, int, float)
15.25
>>> average(5, 10, 15)
TypeWarning:  'average' method returns (float), but result is (int)
15

Needed to cast params as floats in function def (or simply divide by 2.0):

>>> TYPE_CHECK = STRONG
>>> @accepts(int, debug=TYPE_CHECK)
... @returns(int, debug=TYPE_CHECK)
... def fib(n):
...     if n in (0, 1): return n
...     return fib(n-1) + fib(n-2)
...
>>> fib(5.3)
Traceback (most recent call last):
  ...
TypeError: 'fib' method accepts (int), but was given (float)

Functions

accepts(*types, **kw)[source]

Function decorator. Checks that inputs given to decorated function are of the expected type.

Parameters
  • types – The expected type of the decorated function’s return value

  • debug – Optional specification of ‘debug’ level (0 | 1 | 2)

info(fname, expected, actual, flag)[source]

Convenience function returns nicely formatted error/warning msg.

returns(ret_type, **kw)[source]

Function decorator. Checks that return value of decorated function is of the expected type.

Parameters
  • ret_type – The expected type of the decorated function’s return value.

  • debug – Optional specification of ‘debug’ level (0 | 1 | 2)