Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.1 — Objects, Identity and References
Python · Example 3 of 3

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.

01

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.

02

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.

03

Show with three pairs (two int("1000"), two int("7"), two [1] lists) that equal does not mean same object.

04

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

01

What is the difference between == and is, and when is each correct?

02

Is Python pass-by-value or pass-by-reference? Explain with a function that mutates and one that rebinds.

03

Why is def f(x, items=[]) dangerous, and how do you fix it?

04

Why can a is b be True for two small integers but False for two large ones? Should your code rely on this?

05

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?

A shared request template: shallow copy against deepcopy
Sign in to run this example in your browser.

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