A shared request template: shallow copy against deepcopy
A realistic aliasing bug: dict(TEMPLATE) copies only the outer dict, so the inner messages list is shared by every request.
Every value in Python is an object with an identity, a type and a value, and a variable is just a name pointing at an object. Knowing the difference between == (same value) and is (same object) explains aliasing, argument passing and the mutable default argument trap.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Predict the output: a = [1, 2], b = a, b += [3], c = a, c = c + [4]. Print a, b, c, and whether a is b and a is c.
Fix append_to(item, bucket=[]) so each call without a bucket starts with a new empty list. Show that two calls print ['a'] and ['b'], and that a list you pass in is used.
Show with three pairs (two int("1000"), two int("7"), two [1] lists) that equal does not mean same object.
Run t[0] += [3] on t = ([1], 2) inside try/except TypeError. Print the error type name and then t. Explain in a comment why the tuple still changed.
Explain it without notes
What is the difference between == and is, and when is each correct?
Is Python pass-by-value or pass-by-reference? Explain with a function that mutates and one that rebinds.
Why is def f(x, items=[]) dangerous, and how do you fix it?
Why can a is b be True for two small integers but False for two large ones? Should your code rely on this?
What does a += b do for a list, and what does it do for an int or a tuple? Why does t = ([1], 2); t[0] += [3] both fail and succeed?
Expected output
shallow: messages in the second request: 3
shallow: the template itself changed: 3 messages
shallow: shares the list with the template: True
deepcopy: messages in the third request: 2
deepcopy: the template is untouched: 1 message