In this article

Review AI-generated code by tracing inputs, state changes, errors, tests, and the explanation you can defend. This original Python stock-reservation exercise exposes a patch that returns plausible answers while changing the caller’s dictionary, even when it fails. Six executed tests check a narrow repair. Use AI during an interview only when the assessment explicitly permits it.

Write the contract before applying the checklist

Suppose a practice task asks for reserve(stock, item, quantity). Stock is an ordinary dictionary from string item names to nonnegative built-in integer counts. Quantity must be a positive built-in integer, excluding booleans. A successful reservation returns a new dictionary with the selected count reduced; every other count stays the same. The original dictionary must remain unchanged on success and failure.

Agree on failures too: invalid quantity raises ValueError, an unknown item raises KeyError, and insufficient stock raises ValueError. Quantity validation takes precedence when more than one argument is invalid. These choices define this exercise; another repository may specify different exceptions or accept integer subclasses. Read its callers before importing this contract.

The five review checks now have concrete targets. Inputs determine whether arithmetic is allowed. State determines who owns the result. Errors determine what callers can distinguish. Tests supply observations. Explanation connects each changed line to one of those requirements.

    Trace one failed request through the generated patch

    The proposed implementation below looks compact and checks for insufficient stock. Start with stock equal to {"pen": 3}, then request four pens. Subtraction writes minus one into the caller’s dictionary before the function raises. Catching the exception elsewhere cannot undo that earlier write.

    A successful request also violates ownership: requesting two pens returns the original dictionary with its pen count changed to one. Checking only the returned count misses that defect. Make both findings visible before requesting a revision, so the assistant has a behavioral problem to solve rather than a vague instruction to improve quality.

    Deliberately flawed Python reservation
    Codepython
    def reserve(stock, item, quantity):
        stock[item] -= quantity
        if stock[item] < 0:
            raise ValueError("insufficient stock")
        return stock

      Check which values can reach the subtraction

      Requesting minus one pen increases the count. Zero is accepted even though this exercise requires a positive quantity. A fractional quantity produces fractional stock. Strings and None instead trigger incidental TypeErrors. Those outcomes disagree with the stated ValueError contract in different ways; they are not interchangeable evidence of validation.

      True deserves a separate check. Python documents bool as a subclass of int, so an isinstance(quantity, int) guard alone would admit it. Here type(quantity) is int intentionally requires the exact built-in type. That is an application decision, not a universal Python recommendation. Python built-in types: booleans and dictionaries

        Check state after errors as carefully as return values

        An exception test should inspect the state that survives the call. For insufficient stock, save the input, assert ValueError, then compare the dictionary with its original literal contents. For success, compare the returned mapping, verify the original contents, and verify that the returned object has a different identity.

        Unknown items are a useful negative control: the flawed function already raises KeyError before assignment for an ordinary missing key. That passing case does not cancel the other findings. The purpose of review is to identify which obligations hold, not to accumulate an impressive number of green checks.

        Python’s assertRaises fails when no exception occurs and reports a different exception as an error. An unrelated TypeError therefore does not satisfy a ValueError expectation. This distinction keeps a broken test setup from being mistaken for the intended rejection. Python unittest: assertions and exception checks

          Validate first, then change a new mapping

          The repair checks quantity, key presence, and availability before creating the result. Its only subtraction targets the copied dictionary. Exact-stock reservations are allowed and leave zero in the returned mapping; zero remaining stock differs from an invalid zero quantity.

          Dictionary copy is shallow. That is sufficient for this example’s immutable integer values, but it would not isolate nested mutable inventory records. If values become lists or objects, revisit ownership explicitly rather than assuming this line provides deep isolation. Python built-in types: booleans and dictionaries

          Repaired function for the stated practice contract
          Codepython
          def reserve(stock, item, quantity):
              if type(quantity) is not int or quantity <= 0:
                  raise ValueError("quantity must be a positive integer")
              if item not in stock:
                  raise KeyError(item)
              if quantity > stock[item]:
                  raise ValueError("insufficient stock")
              result = stock.copy()
              result[item] -= quantity
              return result

            Run expectations derived from the written contract

            Paste the repaired function above the following standard-library test suite in a Python file and run that file. The six test methods cover a successful copy, exact stock, preserved input after rejection, booleans, other invalid quantities, and an unknown item. Expected dictionaries are literal answers from the task, not values computed by another call to reserve.

            The suite passed on Python 3.14.4 during preparation. Replacing only the function with the flawed version caused assertion failures and wrong-exception errors, including the minus-one stock left after rejection. That experiment checks whether the review evidence detects the demonstrated defect. It does not establish that every possible input or future integration is correct.

            Executable Python checks; place after reserve
            Codepython
            import unittest
            
            class ReservationTests(unittest.TestCase):
                def test_success_returns_new_mapping(self):
                    before = {"pen": 3, "pad": 7}
                    result = reserve(before, "pen", 2)
                    self.assertEqual(result, {"pen": 1, "pad": 7})
                    self.assertEqual(before, {"pen": 3, "pad": 7})
                    self.assertIsNot(result, before)
            
                def test_exact_stock_is_allowed(self):
                    self.assertEqual(reserve({"pen": 3}, "pen", 3), {"pen": 0})
            
                def test_rejected_reservation_preserves_input(self):
                    before = {"pen": 3}
                    with self.assertRaises(ValueError):
                        reserve(before, "pen", 4)
                    self.assertEqual(before, {"pen": 3})
            
                def test_boolean_is_not_a_quantity(self):
                    with self.assertRaises(ValueError):
                        reserve({"pen": 3}, "pen", True)
            
                def test_invalid_quantities(self):
                    for quantity in [0, -1, 1.5, "2", None]:
                        with self.subTest(quantity=quantity):
                            before = {"pen": 3}
                            with self.assertRaises(ValueError):
                                reserve(before, "pen", quantity)
                            self.assertEqual(before, {"pen": 3})
            
                def test_unknown_item(self):
                    before = {"pen": 3}
                    with self.assertRaises(KeyError):
                        reserve(before, "eraser", 1)
                    self.assertEqual(before, {"pen": 3})
            
            if __name__ == "__main__":
                unittest.main()

              Explain the accepted change and its boundary

              A concise practice explanation could be: “I rejected the first patch because it changes shared input before it knows the reservation is valid. I moved validation ahead of arithmetic and changed a copy. The rejection test checks both the exception and surviving input; the success test checks ownership as well as the count.” This is an illustrative explanation, not a reported interview transcript.

              When asking the assistant to revise, keep the public signature and agreed exceptions fixed. Request the validation and copy repair without adding persistence or a new inventory model. Then inspect the diff yourself. A local pure transformation does not prevent two clients from reserving the same real stock; a shared persistent store needs its own atomic reservation design.

                Common questions about reviewing generated interview code

                Should every review use exactly these five checks? Use them as prompts for investigation, adapting them to the task. For this function, ownership and failure state matter. A parser, network client, or concurrent service would add different obligations. Explain the checks that uncover a consequence in the code you actually have.

                Should the assistant write the tests? It can help express already chosen expectations when permitted. Read each assertion and run it against the flawed implementation before accepting the repair. Python’s assertion tools make both content and identity checks available. Python unittest: assertions and exception checks

                Does a green suite make the patch production ready? No. It establishes evidence for this small contract. Integration, persistence, concurrency, and the actual caller’s assumptions remain separate questions. State those limits while showing what the executed checks do support.

                  Sources & editorial notes

                  This article was authored with AI using primary-source research and an automated technical review. It has not been reviewed by a human. Code examples are illustrative; run and verify them in your own environment.

                  1. Python built-in types: booleans and dictionaries

                    Checked October 31, 2026: bool subclasses int; dictionary copy is shallow. These are language semantics, not a new announcement.

                  2. Python unittest: assertions and exception checks

                    Checked October 31, 2026: unittest equality, identity, subtests, and expected-exception behavior support the executable review checks.

                  Put the reading into practice

                  Work through an existing repository, review AI suggestions, and test the decisions behind your changes.

                  Explore practice problems