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."""
raise
statement
raise MyException('error message')
try ... except
statement
# eg. try: from lxml import etree except ModuleNotFoundError as e: # new in version 3.6 from xml import etree
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 (f'Circle(x={self.x}, y={self.y}, radius={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.
Whenever you are tempted to type something into a print
statement or a debugger expression, write it as a test instead.
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, msg='Area of right triangle not correct.') self.assertAlmostEqual(self.triangle_2.area(), 2 * 2 / 2, msg='Area of isosceles triangle not correct.') def test_circumference(self): self.assertAlmostEqual(self.triangle_1.circumference(), 3 + 4 + 5, msg='Circumference of right triangle not' 'correct.') self.assertAlmostEqual(self.triangle_2.circumference(), 2 + 2 * math.sqrt(5), msg='Circumference of isosceles triangle not' 'correct.') if __name__ == "__main__": unittest.main()
setUp()
and tearDown()
python3 test_triangle.py
pytest
assert
statements.