In the following Python 3.8.0.0 script, its is not allowed to change immutable variables from enclosing function scope from sub/nested function, however, modifying mutable types elements works perfectly fine without using nonlocal declaration from sub/nested function. Can someone please explain, why it is like this?
def func():
func_var1 = 18
func_var2 = 'Python'
func_var3 = {1,2,3,4,5,6}
func_var4 = [1,2,3,4,5,6]
func_var5 = {'P': 'Python', 'J': 'Java'}
def sub_func():
nonlocal func_var1
func_var1 = 20
print(func_var1)
nonlocal func_var2
func_var2 = 'Java'
# For mutable types, why does it allow to update variable from enclosing function scope without nonlocal declaration?
func_var3.add(7)
print(func_var3)
func_var4.append(7)
print(func_var4)
func_var5.update({'G':'Go'})
func_var5['R'] = 'Ruby'
print(func_var5)
sub_func()
func()
Output
20
{1, 2, 3, 4, 5, 6, 7}
[1, 2, 3, 4, 5, 6, 7]
{'P': 'Python', 'J': 'Java', 'G': 'Go', 'R': 'Ruby'}