Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. def check_type_hinter(function):
  2. """
  3. Make sure you follow what you said.
  4. How to use:
  5.  
  6. @check_type_hinter
  7. def length(arg: str) -> int:
  8. return len(arg)
  9.  
  10. length('hello')
  11. length(5) # TypeError
  12.  
  13. @cth
  14. def error() -> bool:
  15. return 'an error'
  16. error() # TypeError
  17.  
  18. By math2001
  19. """
  20.  
  21. def class_name(el):
  22. return el.__class__.__name__
  23.  
  24. def caller(*args, **kwargs):
  25. annots = function.__annotations__
  26. i = -1
  27. for arg_name, required_type in annots.items():
  28. if arg_name == 'return':
  29. continue
  30. else:
  31. i += 1
  32.  
  33. if i >= len(args):
  34. break
  35.  
  36. if not isinstance(args[i], required_type):
  37. raise TypeError("The argument '{}' should be a '{}' "
  38. "('{}' given)"
  39. .format(arg_name, required_type.__name__,
  40. class_name(args[i])))
  41.  
  42. result = function(*args, **kwargs)
  43. if (annots.get('return', False) and
  44. not isinstance(result, annots['return'])):
  45. raise TypeError("This function does not return what it should "
  46. "('{}' instead of '{}')".format(class_name(result),
  47. annots['return']
  48. .__name__))
  49.  
  50. return result
  51. caller.__annotations__ = function.__annotations__
  52. return caller
  53.  
  54.  
  55. def cth(*args, **kwargs):
  56. # for the lazy ones (like me)
  57. return check_type_hinter(*args, **kwargs)
  58.  
  59.  
  60. class SomethingCool:
  61.  
  62. def __str__(self):
  63. return "Python's awesome! Let's make it better. ;)"
  64.  
  65.  
  66. @cth
  67. def hello(name: str='you', end='') -> SomethingCool:
  68. msg = 'Hello {}!{}'.format(name, end)
  69. print(msg)
  70. return SomethingCool()
  71.  
  72.  
  73. print(hello())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement