Share Pastebin
Guest
Public paste!

mlk

By: a guest | Jul 23rd, 2008 | Syntax: Python | Size: 0.89 KB | Hits: 60 | Expires: Never
This paste has a previous version, view the difference. Copy text to clipboard
  1. class accepts_wrap(object):
  2.     def __init__(self, func, argtypes):
  3.         self.func = func
  4.         self.__doc__ = func.__doc__
  5.         self.argtypes = argtypes
  6.  
  7.     def __call__(self, *args):
  8.         for i, (arg, cls) in enumerate(zip(args, self.argtypes)):
  9.             if not isinstance(arg, cls):
  10.                 raise TypeError("Expected %r for argument #%d got %r" % (cls, i+1, type(arg)))
  11.         return self.func(*args)
  12.  
  13. def accepts(*argtypes):
  14.     return lambda func: accepts_wrap(func, argtypes)
  15.  
  16.  
  17. @accepts(float, float)
  18. def float_div(a, b):
  19.     """
  20.    A function that divides floats.
  21.    Any other types of arguments will throw an exception
  22.  
  23.        >>> float_div(1.0, 2.0)
  24.        0.5
  25.        >>> float_div(1, 1.0)
  26.        Traceback (most recent call last):
  27.        ...
  28.        TypeError: Expected <type 'float'> for argument #1 got <type 'int'>
  29.    """
  30.     return a / b