Adding Deep Immutability

They will both raise an exception after freezing:

>>> freeze(c2)
>>> 
>>> c2['f']()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f
TypeError: cannot write to local variable 'a'

In this case, it freezes the dictionary, which in turn freezes the two function objects it contains. It then traverses the function objects fields, which includes the variables it has closed over and freezes those.

2 Likes