You are a developer for a financial application that processes transactions. The application uses a dictionary to store account balances where keys are account numbers (strings) and values are floats. A function `transfer(from_acc, to_acc, amount)` is supposed to subtract amount from `from_acc` and add it to `to_acc`. However, some transfers are resulting in incorrect balances: the `from_acc` balance is reduced but the `to_acc` balance is not increased. The code uses `try-except` to catch KeyError if an account does not exist. Upon inspection, the function first checks if both accounts exist, then performs subtraction, then addition, and finally returns success. No exceptions are raised during the problematic transfers. The accounts definitely exist. What is the most likely cause?
Race condition can cause the second update to be lost.
Why this answer
The described symptom — the `from_acc` balance is reduced but the `to_acc` balance is not increased — is a classic race condition. In Python, dictionary operations like `dict[key] -= amount` are not atomic; they involve a read, modify, and write sequence. If two threads execute the transfer function concurrently on overlapping accounts, one thread's write to `to_acc` can be overwritten by another thread's stale read, causing the addition to be lost.
The `try-except` only catches `KeyError`, not data races, and since no exception is raised, the only plausible explanation is unsynchronized concurrent access.
Exam trap
Python Institute often tests the misconception that Python's GIL prevents all concurrency issues, but the trap here is that the GIL does not make compound operations atomic, so race conditions can still occur with dictionary updates.
How to eliminate wrong answers
Option B is wrong because the problem states that no exceptions are raised during the problematic transfers, so the function is not silently returning due to a caught KeyError; the transfers proceed but produce incorrect balances. Option C is wrong because insufficient balance would cause a negative balance in `from_acc`, but the symptom is that `to_acc` is not increased — the subtraction from `from_acc` works correctly, so the issue is not about balance checking. Option D is wrong because if balances were stored as strings, the subtraction operation (`-=`) would raise a TypeError, not silently produce incorrect results; the problem states no exceptions occur, so the types must be correct.