Predict the output
Each call runs once and then is retried once after a timeout. Which line leaves the account in a different state than a single call would?
acct = {"balance": 100}
def put_balance(v: int) -> None:
acct["balance"] = v
def post_deposit(v: int) -> None:
acct["balance"] += v
for f, v in ((put_balance, 150), (post_deposit, 10)):
f(v)
f(v)
print(acct["balance"])Hint 1 of 1
Which one depends on the current value?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A post_deposit: the balance ends at 170, not 160
Correct. Setting a value twice is the same as once; adding twice isn't.
Idempotent means repeating a call leaves the same state as making it once. Setting balance = 150 twice still leaves 150, but adding 10 twice adds 20, so a blind retry of a POST-style deposit double-counts.
Why not the others?
- B
put_balance: the balance ends at 300. PUT-style replacement sets 150 both times. - C Neither: the balance ends at 160. The deposit ran twice.
- D Both change it twice. Replacing with the same value is idempotent.