code_junkie

What is the preferred way to type-check variables in Python

Nov 13th, 2011
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. def isInteger(n):
  2. return int(n) == n
  3.  
  4. isinstance(n, int)
  5.  
  6. type(n) is int
  7.  
  8. return int(n) == n
  9.  
  10. def myintfunction(value):
  11. """ Please pass an integer """
  12. return 2 + value
  13.  
  14. >>> myintfunction(5)
  15. 7
  16.  
  17. >>> myintfunction('text')
  18. Traceback (most recent call last):
  19. File "<stdin>", line 1, in <module>
  20. File "<stdin>", line 3, in myintfunction
  21. TypeError: unsupported operand type(s) for +: 'int' and 'str'
  22.  
  23. >>> print myintfunction(2.2)
  24. 4.2
  25.  
  26. >>> print myintfunction(5j)
  27. (2+5j)
  28.  
  29. >>> import decimal
  30. >>> myintfunction(decimal.Decimal('15'))
  31. Decimal("17")
  32.  
  33. >>> class MyAdderClass(object):
  34. ... def __radd__(self, value):
  35. ... print 'got some value: ', value
  36. ... return 25
  37. ...
  38. >>> m = MyAdderClass()
  39. >>> print myintfunction(m)
  40. got some value: 2
  41. 25
  42.  
  43. def myintfunction(value):
  44. """ Please pass an integer """
  45. return upstreamfunction(int(value))
  46.  
  47. assert isinstance(...)
  48. assert type() is xxxx
  49.  
  50. python -OO program.py
  51.  
  52. class MyInt(int):
  53. # ... extra stuff ...
  54.  
  55. int('sometext')
  56.  
  57. <type 'exceptions.ValueError'>: invalid literal for int() with base 10: 'sometext'
  58.  
  59. try:
  60. int(myvar) + 50
  61. except ValueError:
  62. print "Not a number"
  63.  
  64. if type(n) is int
  65.  
  66. def check_and_convert(x):
  67. x = int(x)
  68. assert 0 <= x <= 255, "must be between 0 and 255 (inclusive)"
  69. return x
  70.  
  71. class IPv4(object):
  72. """IPv4 CIDR prefixes is A.B.C.D/E where A-D are
  73. integers in the range 0-255, and E is an int
  74. in the range 0-32."""
  75.  
  76. def __init__(self, a, b, c, d, e=0):
  77. self.a = check_and_convert(a)
  78. self.b = check_and_convert(a)
  79. self.c = check_and_convert(a)
  80. self.d = check_and_convert(a)
  81. assert 0 <= x <= 32, "must be between 0 and 32 (inclusive)"
  82. self.e = int(e)
Add Comment
Please, Sign In to add comment