def add_to(n): """ Return the sum of all values from 1 to n. """ sum = 0 for i in range(n+1): sum += i return sum # after refacturing def add_to(n): """ Return the sum of all values from 1 to n. """ return (n / 2.0) * (n + 1)
class MyException(Exception): """An exception which is specific to this program.""" pass
raise
statement
raise MyException('error message')
try ... except
statement
# eg. try: import a_module except (RuntimeError, ImportError) as e: import an_alternative as a_module # not as good as a_module
1 / 0
float('hello')
1 + 'fail'
open("nonexisting.file", 'r')
import math; math.log(-1)
raise ValueError('number must be greater than 0')
#!/usr/bin/env python3 class InvalidCircleException(Exception): """This exception is for Circles with a radius < 0.""" pass class Circle(object): def __init__(self, x, y, radius): self.x = x self.y = y self.radius = radius # this is now safe def __str__(self): return ("Circle(x={}, y={}, radius={})" .format(self.x, self.y, self.radius)) @property def radius(self): return self.__radius @radius.setter def radius(self, radius): """Ensure that `radius` is valid.""" if radius < 0: raise InvalidCircleException("radius must be >= 0") self.__radius = radius if __name__ == "__main__": a_circle = Circle(25, 15, 7) # ok print(a_circle) another_circle = Circle(25, 15, -7) # not allowed anymore
Certitude is not the test of certainty. We have been cocksure of many things that were not so.
unittest.TestCase
#!/usr/bin/env python3 import math import unittest from inheritance import Point, Triangle class TestTriangle(unittest.TestCase): def setUp(self): A = Point(0, 0) B = Point(4, 0) C = Point(0, 3) self.triangle_1 = Triangle(A, B, C) # right triangle self.triangle_2 = Triangle(A, Point(2, 0), Point(1, 2)) # isosceles triangle def test_area(self): self.assertAlmostEqual(self.triangle_1.area(), 3 * 4 / 2) self.assertAlmostEqual(self.triangle_2.area(), 2 * 2 / 2) def test_circumference(self): self.assertAlmostEqual(self.triangle_1.circumference(), 3 + 4 + 5) self.assertAlmostEqual(self.triangle_2.circumference(), 2 + 2 * math.sqrt(5)) if __name__ == "__main__": unittest.main()
setUp()
and tearDown()
python3 test_triangle.py
nose