how to make a calculator 8

I can use the __getattribute__ method that comes with every Python object in the calculator tests


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    @staticmethod
 13    def get_division_result(x, y):
 14        try:
 15            return x / y
 16        except ZeroDivisionError:
 17            return 'brmph?! I cannot divide by 0. Try again...'
 18
 19    def setUp(self):
 20        self.random_first_number = a_random_number()
 21        self.random_second_number = a_random_number()
 22
 23        x = self.random_first_number
 24        y = self.random_second_number
 25
 26        self.calculator_tests = {
 27            'add': x+y,
 28            'subtract': x-y,
 29            'multiply': x*y,
 30            'divide': self.get_division_result(x, y)
 31        }
 32
 33    def test_calculator_w_list_items(self):
 34        # two_numbers = [
 35        #     self.random_first_number,
 36        #     self.random_second_number
 37        # ]
 38        a_dictionary = {
 39            'x': self.random_first_number,
 40            'y': self.random_second_number
 41        }
 42        two_numbers = list(a_dictionary.values())
 43
 44        for operation in self.calculator_tests:
 45            with self.subTest(operation=operation):
 46                self.assertEqual(
 47                    src.calculator.__getattribute__(operation)(
 48                        *two_numbers
 49                    ),
 50                    self.calculator_tests[operation]
 51                )
 52
 53        self.assertEqual(
 54            src.calculator.add(
 55                two_numbers[0],
 56                two_numbers[1]
 57            ),
 58            self.random_first_number+self.random_second_number
 59        )
 60        self.assertEqual(
 61            src.calculator.divide(
 62                two_numbers[-2],
 63                two_numbers[-1]
 64            ),
 65            self.random_first_number/self.random_second_number
 66        )
 67        self.assertEqual(
 68            src.calculator.multiply(
 69                two_numbers[1],
 70                two_numbers[-1]
 71            ),
 72            self.random_second_number*self.random_second_number
 73        )
 74        self.assertEqual(
 75            src.calculator.subtract(
 76                two_numbers[-2],
 77                two_numbers[0]
 78            ),
 79            self.random_first_number-self.random_first_number
 80        )
 81
 82    def test_calculator_w_dictionary_items(self):
 83        two_numbers = {
 84            'first_input': self.random_first_number,
 85            'second_input': self.random_second_number,
 86        }
 87
 88        for operation in self.calculator_tests:
 89            with self.subTest(operation=operation):
 90                self.assertEqual(
 91                    src.calculator.__getattribute__(operation)(
 92                        **two_numbers
 93                    ),
 94                    self.calculator_tests[operation]
 95                )
 96
 97        self.assertEqual(
 98            src.calculator.add(
 99                two_numbers['first_input'],
100                two_numbers['second_input']
101            ),
102            self.random_first_number+self.random_second_number
103        )
104        self.assertEqual(
105            src.calculator.divide(
106                two_numbers['first_input'],
107                two_numbers['second_input']
108            ),
109            self.random_first_number/self.random_second_number
110        )
111        self.assertEqual(
112            src.calculator.multiply(
113                two_numbers['second_input'],
114                two_numbers['second_input']
115            ),
116            self.random_second_number*self.random_second_number
117        )
118        self.assertEqual(
119            src.calculator.subtract(
120                two_numbers['first_input'],
121                two_numbers['first_input']
122            ),
123            self.random_first_number-self.random_first_number
124        )
125
126    def test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputs(self):
127        for operation in self.calculator_tests:
128            with (
129                self.subTest(operation=operation),
130                self.assertRaises(TypeError),
131            ):
132                src.calculator.__getattribute__(operation)(
133                    [0, 1, 2]
134                )
135
136    def test_calculator_sends_message_when_input_is_not_a_number(self):
137        for bad_input in (
138            None,
139            True, False,
140            str(), 'text',
141            tuple(), (0, 1, 2, 'n'),
142            list(), [0, 1, 2, 'n'],
143            set(), {0, 1, 2, 'n'},
144            dict(), {'key': 'value'},
145        ):
146            for operation in self.calculator_tests:
147                with self.subTest(
148                    operation=operation,
149                    bad_input=bad_input,
150                ):
151                    self.assertEqual(
152                        src.calculator.__getattribute__(operation)(
153                            bad_input, a_random_number()
154                        ),
155                        'brmph?! Numbers only. Try again...'
156                    )
157
158    def test_calculator_functions(self):
159        for operation in self.calculator_tests:
160            with self.subTest(operation=operation):
161                self.assertEqual(
162                    src.calculator.__getattribute__(operation)(
163                        self.random_first_number,
164                        self.random_second_number
165                    ),
166                    self.calculator_tests[operation]
167                )
168
169
170# Exceptions seen
171# AssertionError
172# NameError
173# AttributeError
174# TypeError
175# KeyError

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

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


test_calculator_w_getattribute

RED: make it fail


I add a new test

168    def test_calculator_functions(self):
169        for operation in self.arithmetic_tests:
170            with self.subTest(operation=operation):
171                self.assertEqual(
172                    self.arithmetic_tests[operation]['function'](
173                        self.random_first_number,
174                        self.random_second_number
175                    ),
176                    self.arithmetic_tests[operation]['expectation']
177                )
178
179    def test_calculator_w_getattribute(self):
180        self.assertEqual(
181            src.calculator.__getattribute__('BOOM!!!'),
182            src.calculator.add
183        )
184
185
186# Exceptions seen

the terminal is my friend, and shows AttributeError

terminal
AttributeError: module 'src.calculator' has no attribute 'BOOM!!!'
  • __getattribute__ is a method that takes a name and checks if the name is an attribute of the object

  • src.calculator.__getattribute__('BOOM!!!') checks if the calculator.py module in the src folder has anything named BOOM!!!


GREEN: make it pass


I change 'BOOM!!!' to 'add'

179      def test_calculator_w_getattribute(self):
180          self.assertEqual(
181              src.calculator.__getattribute__('add'),
182              src.calculator.add
183          )

the test passes because the add function is an attribute of src.calculator


REFACTOR: make it better


  • I add a call to the add function

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: <function numbers_only.<locals>.decorator at 0xffffa1234bc0> != DEF.GHIJKLMNOPQRS
    

    I have to call the add function after __getattribute__ returns it

  • I add parentheses at the end of the line to make it a call

    the test passes.

  • I add a variables and a dictionary

  • I use the dictionary to change the expectation of the assertion

    the test is still green.

  • I use the variables for self.random_first_number and self.random_second_number in the assertion

    still green.

  • I remove the commented lines

    green.





  • I add a for loop

    the terminal is my friend, and shows AssertionError

    SUBFAILED(operation='add') ...      - AssertionError: FGH.IJKLMNOPQRSTU != 'BOOM!!!'
    SUBFAILED(operation='subtract') ... - AssertionError: VWX.YZABCDEFGHIJKL != 'BOOM!!!'
    SUBFAILED(operation='multiply') ... - AssertionError: MNOP.QRSTUVWXYZAB != 'BOOM!!!'
    SUBFAILED(operation='divide') ...   - AssertionError: CD.EFGHIJKLMNOPQR != 'BOOM!!!'
    
  • I change the expectation

    the test passes.

  • I remove the other assertions

    is this simpler than test_calculator_functions?








  • I comment out self.arithmetic_tests in the `setUp method`_ to see if there are any tests that still use it

    the tests are still green.

  • I remove the commented lines


all the tests are passing and I feel like magic


test calculator tests again

I want to write the solution that will make all the tests in test_calculator.py pass without looking at them


RED: make it fail


  • I close test_calculator.py

  • I open calculator.py from the src folder

  • then I delete everything in calculator.py, the terminal is my friend, and shows 3 passing tests and AttributeError for 70 failing tests, I start with the last one

    terminal
    AttributeError: module 'src.calculator' has no attribute 'add'
    
  • I add the name to calculator.py

    1add
    

    the terminal is my friend, and shows NameError

    terminal
    NameError: name 'add' is not defined
    

GREEN: make it pass


  • I point add to None to define it

    1add = None
    

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: 'NoneType' object is not callable
    
  • I change it to a function

    1def add():
    2    return None
    

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: add() takes 0 positional arguments but 2 were given
    
  • I add a name to the parentheses

    1def add(x):
    2    return None
    

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: add() takes 1 positional argument but 2 were given
    
  • I add a second name to the parentheses

    1def add(x, y):
    2    return None
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: None != TUV.WXYZABCDEFGHIJ
    
  • I change the return statement

    1def add(x, y):
    2    return x + y
    

    the terminal shows AttributeError

    terminal
    AttributeError: module 'src.calculator' has no attribute 'divide'
    
  • I add a function

    1def add(x, y):
    2    return x + y
    3
    4
    5def divide(x, y):
    6    return x / y
    

    the terminal is my friend, and shows AttributeError

    terminal
    AttributeError: module 'src.calculator' has no attribute 'multiply'
    
  • I add a function

    the terminal is my friend, and shows AttributeError

    terminal
    AttributeError: module 'src.calculator' has no attribute 'subtract'
    
  • I add a function for it

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: divide() got an unexpected keyword argument 'first_input'
    

  • I add a name to the divide function

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: divide() missing 1 required positional argument: 'first_input'
    
  • I add a default value to make it a choice

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: divide() got an unexpected keyword argument 'second_input'
    
  • I add second_input with a default value to the function

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: divide() missing 2 required positional arguments: 'x' and 'y'
    
  • the test must be calling divide with positional arguments in some cases and with keyword arguments in others. My solution does not work, I remove x and y from the parentheses

    the terminal is my friend, and shows NameError

    terminal
    NameError: name 'x' is not defined
    
  • I change the names in the return statement

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: multiply() got an unexpected keyword argument 'first_input'
    
  • I use the Rename Symbol feature to change the names in the parentheses

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: divide() got an unexpected keyword argument 'second_input'
    
  • I do the same thing to y

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: subtract() got an unexpected keyword argument 'first_input'
    

    same problem, same solution

  • I change the names

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: add() got an unexpected keyword argument 'first_input'
    
  • I change the names in the add function

    1def add(first_input, second_input):
    2    return first_input + second_input
    

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='divide', bad_input={'key': 'value'}) ... - TypeError: unsupported operand type(s) for /: 'dict' and 'float'
    

  • I add an if statement to the divide function

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: None != 'brmph?! Numbers only. Try again...'
    
  • I change the return statement of the if statement

    1def add(first_input, second_input):
    2    if isinstance(first_input, dict):
    3        return 'brmph?! Numbers only. Try again...'
    4    return first_input + second_input
    

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='multiply', bad_input={'key': 'value'}) ... - TypeError: unsupported operand type(s) for *: 'dict' and 'float'
    
  • I add an if statement to the multiply function

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: None != 'brmph?! Numbers only. Try again...'
    
  • I change the return statement of the if statement

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='subtract', bad_input={'key': 'value'}) ... - TypeError: unsupported operand type(s) for -: 'dict' and 'float'
    

    same problem, same solution

  • I add an if statement with the same message in the subtract function

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='add', bad_input={'key': 'value'}) ... - TypeError: unsupported operand type(s) for +: 'dict' and 'float'
    
  • I add the same if statement to the add function

    1def add(first_input, second_input):
    2    if isinstance(first_input, dict):
    3        return 'brmph?! Numbers only. Try again...'
    4    return first_input + second_input
    

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='divide', bad_input={'n', 0, 2, 1}) ... - TypeError: unsupported operand type(s) for /: 'set' and 'float'
    

  • I add set to the if statement in the divide function

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='multiply', bad_input={0, 1, 2, 'n'}) ... - TypeError: unsupported operand type(s) for *: 'set' and 'float'
    
  • I do the same thing to the if statement in the multiply function

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='subtract', bad_input={0, 1, 2, 'n'}) ... - TypeError: unsupported operand type(s) for -: 'set' and 'float'
    
  • I change the if statement in the subtract function

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='add', bad_input={0, 1, 2, 'n'}) ... - TypeError: unsupported operand type(s) for +: 'set' and 'float'
    
  • I add set to the if statement in the add function

    1def add(first_input, second_input):
    2    if isinstance(first_input, (dict, set)):
    3        return 'brmph?! Numbers only. Try again...'
    4    return first_input + second_input
    

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='divide', bad_input=[0, 1, 2, 'n']) ... - TypeError: unsupported operand type(s) for /: 'list' and 'float'
    

  • I add list to the if statement of the divide function

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='multiply', bad_input=[0, 1, 2, 'n']) ... - TypeError: can't multiply sequence by non-int of type 'float'
    

    the error message is different and the function got [0, 1, 2, 'n'] as input, it looks I will have to do this for all the other operations

  • I add list to the if statement in the other functions

     1def add(first_input, second_input):
     2    if isinstance(first_input, (dict, set, list)):
     3        return 'brmph?! Numbers only. Try again...'
     4    return first_input + second_input
     5
     6
     7def divide(first_input=None, second_input=None):
     8    if isinstance(first_input, (dict, set, list)):
     9        return 'brmph?! Numbers only. Try again...'
    10    return first_input / second_input
    11
    12
    13def multiply(first_input, second_input):
    14    if isinstance(first_input, (dict, set, list)):
    15        return 'brmph?! Numbers only. Try again...'
    16    return first_input * second_input
    17
    18
    19def subtract(first_input, second_input):
    20    if isinstance(first_input, (dict, set, list)):
    21        return 'brmph?! Numbers only. Try again...'
    22    return first_input - second_input
    

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='divide', bad_input=(0, 1, 2, 'n')) ... - TypeError: unsupported operand type(s) for /: 'tuple' and 'float'
    

    another data type, there has to be a better way



  • I add str to the if statements of the 4 functions

     1def add(first_input, second_input):
     2    if isinstance(first_input, (dict, set, list, tuple, str)):
     3        return 'brmph?! Numbers only. Try again...'
     4    return first_input + second_input
     5
     6
     7def divide(first_input=None, second_input=None):
     8    if isinstance(first_input, (dict, set, list, tuple, str)):
     9        return 'brmph?! Numbers only. Try again...'
    10    return first_input / second_input
    11
    12
    13def multiply(first_input, second_input):
    14    if isinstance(first_input, (dict, set, list, tuple, str)):
    15        return 'brmph?! Numbers only. Try again...'
    16    return first_input * second_input
    17
    18
    19def subtract(first_input, second_input):
    20    if isinstance(first_input, (dict, set, list, tuple, str)):
    21        return 'brmph?! Numbers only. Try again...'
    22    return first_input - second_input
    

    the terminal is my friend, and shows AssertionError

    terminal
    SUBFAILED(operation='divide', bad_input=False) ... - AssertionError: 0.0 != 'brmph?! Numbers only. Try again...'
    

    the input is a boolean in this case


  • I use the bool built-in function to the if statements of the functions

     1def add(first_input, second_input):
     2    if isinstance(
     3        first_input,
     4        (dict, set, list, tuple, str, bool)
     5    ):
     6        return 'brmph?! Numbers only. Try again...'
     7    return first_input + second_input
     8
     9
    10def divide(first_input=None, second_input=None):
    11    if isinstance(
    12        first_input,
    13        (dict, set, list, tuple, str, bool)
    14    ):
    15        return 'brmph?! Numbers only. Try again...'
    16    return first_input / second_input
    17
    18
    19def multiply(first_input, second_input):
    20    if isinstance(
    21        first_input,
    22        (dict, set, list, tuple, str, bool)
    23    ):
    24        return 'brmph?! Numbers only. Try again...'
    25    return first_input * second_input
    26
    27
    28def subtract(first_input, second_input):
    29    if isinstance(
    30        first_input,
    31        (dict, set, list, tuple, str, bool)
    32    ):
    33        return 'brmph?! Numbers only. Try again...'
    34    return first_input - second_input
    

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='divide', bad_input=None) ... - TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'
    

  • I add None to the call to the isinstance built-in function in the if statement of the divide function

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
    

    I cannot use None in the isinstance built-in function

  • I undo the change then add a new condition

    the terminal is my friend, and shows TypeError

    terminal
    SUBFAILED(operation='multiply', bad_input=None) ... - TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'
    

    same problem, same …

  • I add the new condition to the if statement of the other functions

     1def add(first_input, second_input):
     2    if isinstance(
     3        first_input,
     4        (dict, set, list, tuple, str, bool)
     5    ) or first_input is None:
     6        return 'brmph?! Numbers only. Try again...'
     7    return first_input + second_input
     8
     9
    10def divide(first_input=None, second_input=None):
    11    if isinstance(
    12        first_input,
    13        (dict, set, list, tuple, str, bool)
    14    ) or first_input is None:
    15        return 'brmph?! Numbers only. Try again...'
    16    return first_input / second_input
    17
    18
    19def multiply(first_input, second_input):
    20    if isinstance(
    21        first_input,
    22        (dict, set, list, tuple, str, bool)
    23    ) or first_input is None:
    24        return 'brmph?! Numbers only. Try again...'
    25    return first_input * second_input
    26
    27
    28def subtract(first_input, second_input):
    29    if isinstance(
    30        first_input,
    31        (dict, set, list, tuple, str, bool)
    32    ) or first_input is None:
    33        return 'brmph?! Numbers only. Try again...'
    34    return first_input - second_input
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: TypeError not raised
    
  • I remove the default values from the divide function because it is the only one that is different from the others

    the test passes. Time to play


REFACTOR: make it better


  • I add a decorator function

     1def check_input(function):
     2    def wrapper(first_input, second_input):
     3        if isinstance(
     4            first_input,
     5            (dict, set, list, tuple, str, bool)
     6        ) or first_input is None:
     7            return 'brmph?! Numbers only. Try again...'
     8        return function(first_input, second_input)
     9    return wrapper
    10
    11
    12def add(first_input, second_input):
    
  • I use it to wrap the add function

    the test is still green.

  • I remove the if statement

    still green.

  • I do the same thing to the divide function

    green.

  • I remove the if statement

    the test is still green.

  • I make the same change to the other 2 functions

     1def check_input(function):
     2    def wrapper(first_input, second_input):
     3        if (
     4            isinstance(
     5                first_input,
     6                (dict, set, list, tuple, str, bool)
     7            ) or
     8            first_input is None
     9        ):
    10            return 'brmph?! Numbers only. Try again...'
    11        return function(first_input, second_input)
    12    return wrapper
    13
    14
    15@check_input
    16def add(first_input, second_input):
    17    return first_input + second_input
    18
    19
    20@check_input
    21def divide(first_input, second_input):
    22    return first_input / second_input
    23
    24
    25@check_input
    26def multiply(first_input=None, second_input=None):
    27    return first_input * second_input
    28
    29
    30@check_input
    31def subtract(first_input, second_input):
    32    return first_input - second_input
    

    still green.


All the tests are passing, and there are problems

I wonder what else I missed. I am still learning


close the project

  • I close test_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

  • I used the __getattribute__ built-in function to make the calculator tests simpler.

  • I rewrote the solution after rewriting the tests and found that

    • I did not add a test for bad second inputs

    • the test for handling ZeroDivisionError has a problem


code from the chapter

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


what is next?

Would you like to know what causes ModuleNotFoundError?


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.