Inadvertent Sharing Is Source Of Many Bugs: SICP Lecture Illustrated with Python’s Colon Copy Idiom

The aim of this page📝 is to give Python’s illustration of the great rant of prof. Sussman about the dangers of inadvertent sharing in SICP Lecture 5b: Computational Objects

1. notes

inadvertent sharing — unanticipated interactions between objects — is the source of many bugs in complicated programs — by introducing possibility of things having identity (assignment) and sharing and having multiple names for the same things we get a lot of power. but we have to pay for it with lots of complexity and bugs

>>> l = [[1,2,3], [4,5,6]]      # OLD LIST
>>> l1 = l[:] # NEW LIST
>>> l1.append([7,8,9]) # <<< ALL GOOD - ONLY L1 MODIFIED
>>> l1
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> l
[[1, 2, 3], [4, 5, 6]]
>>> l1[0].append(666) # <<< OU SH1T - 666 LEAKED INTO L, TOO !
>>> l1
[[1, 2, 3, 666], [4, 5, 6], [7, 8, 9]]
>>> l
[[1, 2, 31, 666], [4, 5, 6]]
shallow-copy visualized — safe for immutables items, tricky for mutables items (when elements of collections are themselves lists/dicts/sets)

2. links

Technical Support Engineer/Technical Writer (Snowplow Analytics). with a passion for Python / writing documentation. More about me: https://pavol.kutaj.com