how to make a calculator 4

I want to use TypeError with exception handlers to make sure that the calculator program only works with numbers, like a Calculator in the real world.


preview

I have these tests by the end of the chapter

 1import random
 2import src.calculator
 3import unittest
 4
 5
 6def a_random_number():
 7    return random.triangular(-1000.0, 1000.0)
 8
 9
10class TestCalculator(unittest.TestCase):
11
12    random_first_number = a_random_number()
13    random_second_number = a_random_number()
14
15    def test_addition(self):
16        self.assertEqual(
17            src.calculator.add(
18                self.random_first_number,
19                self.random_second_number
20            ),
21            self.random_first_number+self.random_second_number
22        )
23
24    def test_subtraction(self):
25        self.assertEqual(
26            src.calculator.subtract(
27                self.random_first_number,
28                self.random_second_number
29            ),
30            self.random_first_number-self.random_second_number
31        )
32
33    def test_multiplication(self):
34        self.assertEqual(
35            src.calculator.multiply(
36                self.random_first_number,
37                self.random_second_number
38            ),
39            self.random_first_number*self.random_second_number
40        )
41
42    def test_division(self):
43        try:
44            self.assertEqual(
45                src.calculator.divide(
46                    self.random_first_number,
47                    self.random_second_number
48                ),
49                self.random_first_number/self.random_second_number
50            )
51        except ZeroDivisionError:
52            self.assertEqual(
53                src.calculator.divide(self.random_first_number, 0),
54                'brmph?! I cannot divide by 0. Try again...'
55            )
56
57    def test_calculator_sends_message_when_input_is_not_a_number(self):
58        error_message = 'brmph?! Numbers only. Try again...'
59
60        self.assertEqual(
61            src.calculator.add(None, None),
62            error_message
63        )
64        self.assertEqual(
65            src.calculator.divide(None, None),
66            error_message
67        )
68        self.assertEqual(
69            src.calculator.multiply(None, None),
70            error_message
71        )
72        self.assertEqual(
73            src.calculator.subtract(None, None),
74            error_message
75        )
76        self.assertEqual(
77            src.calculator.add('1', '1'),
78            error_message
79        )
80        self.assertEqual(
81            src.calculator.divide('1', '1'),
82            error_message
83        )
84        self.assertEqual(
85            src.calculator.multiply('1', '1'),
86            error_message
87        )
88        self.assertEqual(
89            src.calculator.subtract('1', '1'),
90            error_message
91        )
92
93
94# Exceptions seen
95# AssertionError
96# NameError
97# AttributeError
98# TypeError

open the project

  • I change directory to the calculator folder

    terminal
    cd calculator
    

    the terminal shows I am in the calculator folder

    .../pumping_python/calculator
    
  • I use pytest-watcher to run the tests

    terminal
    uv run pytest-watcher . --now --patterns "**/*.py"
    

    the terminal is my friend, and shows

    terminal
    rootdir: .../pumping_python/calculator
    configfile: pyproject.toml
    collected 4 items
    
    tests/test_calculator.py ....                                        [100%]
    
    ======================== 4 passed in X.YZs =========================
    
  • I hold ctrl on the keyboard, then click on tests/test_calculator.py to open it


test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none

RED: make it fail


I add a new failing test to show that the calculator raises TypeError when one of the inputs is None, just like in test_type_error_w_objects_that_do_not_mix

42    def test_division(self):
43        try:
44            self.assertEqual(
45                src.calculator.divide(
46                    self.random_first_number,
47                    self.random_second_number
48                ),
49                self.random_first_number/self.random_second_number
50            )
51        except ZeroDivisionError:
52            self.assertEqual(
53                src.calculator.divide(self.random_first_number, 0),
54                'brmph?! I cannot divide by 0. Try again...'
55            )
56
57    def test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none(self):
58        src.calculator.add(None, None)
59
60
61# Exceptions seen

the terminal is my friend, and shows TypeError

terminal
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

GREEN: make it pass


I add assertRaises

57    def test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none(self):
58        with self.assertRaises(TypeError):
59            src.calculator.add(None, None)

the test passes.


REFACTOR: make it better


The calculator raises TypeError when None is given as input.

What does it do if the input is a boolean, string, tuple, list, set or a dictionary?


test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_strings

RED: make it fail


I add a new test with an assertion from test_assert_keyword, to test the add function with strings

64        with self.assertRaises(TypeError):
65            src.calculator.subtract(None, None)
66
67    def test_calculator_with_strings(self):
68        self.assertEqual(src.calculator.add('1', '1'), '2')
69
70
71# Exceptions seen

the terminal is my friend, and shows AssertionError

terminal
AssertionError: '11' != '2'

GREEN: make it pass


I change the expectation to match reality

67    def test_calculator_with_strings(self):
68        self.assertEqual(src.calculator.add('1', '1'), '11')

the test passes.


REFACTOR: make it better



how to test if something is an instance of an object in a program

I want the add function to raise TypeError when it gets a string, the same way the other functions raise TypeError when one of the inputs is a string. I can use the `isinstance function`_ which is like the assertIsInstance method from when I tested None, it checks if one thing is an instance or child of an object


test_calculator_sends_message_when_input_is_not_a_number

I want the calculator functions to send a message when it gets something that is not a number, not raise TypeError which causes the program to stop. I want the user to be able to try again with different input.


RED: make it fail


I change the assertRaises to assertEqual method for the add function in test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none

57    def test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none(self):
58        self.assertEqual(
59            src.calculator.add(None, None),
60            'brmph?! Numbers only. Try again...'
61        )
62        with self.assertRaises(TypeError):
63            src.calculator.divide(None, None)
64        with self.assertRaises(TypeError):
65            src.calculator.multiply(None, None)
66        with self.assertRaises(TypeError):
67            src.calculator.subtract(None, None)

the terminal is my friend, and shows TypeError

terminal
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

GREEN: make it pass


I add an exception handler to the else clause of the add function in calculator.py

16def add(first_input, second_input):
17    if (
18        isinstance(first_input, str)
19        or
20        isinstance(second_input, str)
21    ):
22        raise TypeError
23    else:
24        try:
25            return first_input + second_input
26        except TypeError:
27            return 'brmph?! Numbers only. Try again...'

the test passes.


REFACTOR: make it better





  • I add a variable

  • I use it to remove the repetition of the error message

    the test is still green.


what is a decorator function?

3 of the functions in the calculator program have the same if statement

if first_input is None or second_input is None:
    return 'brmph?! Numbers only. Try again...'

How can I remove this repetition? The only difference between the 3 functions is in what they do with the inputs

return first_input - second_input
return first_input * second_input
return first_input / second_input

I can use a decorator/wrapper function to remove the repetition from those 3 functions. It is a function that takes another function as input.

  • I add a decorator function to calculator.py

    1def input_is_not_none(function):
    2    def wrapper(first_input, second_input):
    3        if first_input is None or second_input is None:
    4            return 'brmph?! Numbers only. Try again...'
    5        return function(first_input, second_input)
    6    return wrapper
    7
    8
    9def subtract(first_input, second_input):
    

    The input_is_not_none function

  • I use it with the subtract function

    the tests are still green.

  • I remove the if statement from the subtract function

    still green.

  • I use input_is_not_none with the multiply function

    green.

  • I remove the if statement from the multiply function

    still green.

  • I wrap the divide function with input_is_not_none

    the tests are still green.

  • I remove the if statement

     1def input_is_not_none(function):
     2    def wrapper(first_input, second_input):
     3        if first_input is None or second_input is None:
     4            return 'brmph?! Numbers only. Try again...'
     5        return function(first_input, second_input)
     6    return wrapper
     7
     8
     9@input_is_not_none
    10def subtract(first_input, second_input):
    11    return first_input - second_input
    12
    13
    14@input_is_not_none
    15def multiply(first_input, second_input):
    16    return first_input * second_input
    17
    18
    19@input_is_not_none
    20def divide(first_input, second_input):
    21    try:
    22        return first_input / second_input
    23    except ZeroDivisionError:
    24        return 'brmph?! I cannot divide by 0. Try again...'
    25
    26
    27def add(first_input, second_input):
    28    if (
    29        isinstance(first_input, str)
    30        or
    31        isinstance(second_input, str)
    32    ):
    33        return 'brmph?! Numbers only. Try again...'
    34    else:
    35        try:
    36            return first_input + second_input
    37        except TypeError:
    38            return 'brmph?! Numbers only. Try again...'
    

    still green.





3 of the functions in the calculator program have the same exception handler

try:
    something
except TypeError:
    return 'brmph?! Numbers only. Try again...'

the divide function is different because it has another except clause

terminal
except ZeroDivision:
    return 'brmph?! I cannot divide by 0. Try again...'

I can use a decorator/wrapper function to remove the repetition of the exception handler from the functions


  • The two decorator functions both return the result of calling the given functions or an error message

    return function(first_input, second_input)
    return 'brmph?! Numbers only. Try again...'
    

    I make a new decorator to do the work of type_error_handler and input_is_not_none

     1def numbers_only(function):
     2    def decorator(first_input, second_input):
     3        error_message = 'brmph?! Numbers only. Try again...'
     4        if first_input is None or second_input is None:
     5            return error_message
     6        else:
     7            try:
     8                return function(first_input, second_input)
     9            except TypeError:
    10                return error_message
    11    return decorator
    12
    13
    14def type_error_handler(function):
    

    The numbers_only function

  • I use numbers_only to wrap the subtract function

    the tests are still green.

  • I remove the other wrappers from the subtract function

    still green.

  • I wrap the multiply function

    green.

  • I remove the other wrappers from the multiply function

    still green.

  • I wrap the divide function

    the tests are still green.

  • I remove the other wrappers from the divide function

    still green.

  • I wrap the add function

    green.

  • I remove the other wrappers from the add function

    still green.

  • I remove type_error_handler and input_is_not_none because they are no longer used

     1def numbers_only(function):
     2    def decorator(first_input, second_input):
     3        error_message = 'brmph?! Numbers only. Try again...'
     4        if first_input is None or second_input is None:
     5            return error_message
     6        else:
     7            try:
     8                return function(first_input, second_input)
     9            except TypeError:
    10                return error_message
    11    return decorator
    12
    13
    14@numbers_only
    15def subtract(first_input, second_input):
    

    all tests are still green.



  • I can make a function for the condition in the if statement in the add function in calculator.py

  • then use is_string in the add function

    the test is still green. This removes the repetition of str in the call to the `isinstance function`_

    isinstance(first_input, str)
    isinstance(second_input, str)
    

    it also adds 2 lines of code to remove 6 characters. WOW!

  • I undo the change

  • I can make a function for the if statement in the add function

  • then use one_input_is_a_string in the add function

    the test is still green. the one_input_is_a_string function

  • enough experiments for now. I undo the change because I do not need it

     1def numbers_only(function):
     2    def decorator(first_input, second_input):
     3        error_message = 'brmph?! Numbers only. Try again...'
     4        if first_input is None or second_input is None:
     5            return error_message
     6        else:
     7            try:
     8                return function(first_input, second_input)
     9            except TypeError:
    10                return error_message
    11    return decorator
    12
    13
    14@numbers_only
    15def subtract(first_input, second_input):
    16    return first_input - second_input
    17
    18
    19@numbers_only
    20def multiply(first_input, second_input):
    21    return first_input * second_input
    22
    23
    24@numbers_only
    25def divide(first_input, second_input):
    26    try:
    27        return first_input / second_input
    28    except ZeroDivisionError:
    29        return 'brmph?! I cannot divide by 0. Try again...'
    30
    31
    32@numbers_only
    33def add(first_input, second_input):
    34    if (
    35        isinstance(first_input, str)
    36        or
    37        isinstance(second_input, str)
    38    ):
    39        return 'brmph?! Numbers only. Try again...'
    40    else:
    41        return first_input + second_input
    

    and all the tests are still passing. The world is my oyster!


close the project

  • I close test_calculator.py and calculator.py

  • I click in the terminal where the tests are running

  • I use q on the keyboard to leave the tests. The terminal goes back to the command line.

  • I change directory to the parent of calculator

    terminal
    cd ..
    

    the terminal is my friend, and shows

    .../pumping_python
    

    I am back in the pumping_python directory.


review

The calculator program can take 2 inputs and check if they are both numbers, then add, subtract, multiply or divide them

Even though the program says it only works with numbers, I did not add tests for tuples, lists, sets, and dictionaries, though they are touched in test_type_error_w_objects_that_do_not_mix, Do you want to add them or do we already have enough tests to know what would happen?


code from the chapter

Do you want to see all the CODE I typed in this chapter?


what is next?

Would you like to test Lists?


rate pumping python

If this has been a 7 star experience for you, please CLICK HERE to leave a 5 star review of pumping python. It helps other people get into the book too.