-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmod_01_mutables_vs_immutables.py
453 lines (320 loc) · 11.9 KB
/
mod_01_mutables_vs_immutables.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#-*- coding: utf-8 -*-
###
# MODULE 01: Objects: type, id, value, mutable vs. immutable
###
# Let's instantiate a string and check its identity, type and value
str_inst = 'abcd'
print "identity:", id(str_inst)
print "type:", type(str_inst)
print "value:", str_inst
# Let's use the 'is' operator
print str_inst is 'abcd'
# What happened here?
# Let's compare the ids of two int values
int_inst_1 = 7
int_inst_2 = 7
print int_inst_1 is int_inst_2
print int_inst_1 is 7
print id(int_inst_1), 'vs.', id(int_inst_2)
# Why both have the same id?
#===============================================================================
# - Every object has an identity (its address up to now), a type and a value
# - Both id and type are unchangeable
# - Use 'id' function to retrieve the id of an object
# - Use 'type' function to retrieve the type of an object
# - Remeber to be Pythonic (Duck Typing, EAFP...)
# - Use 'is' operator to compare the id of two objects
# - The interpreter may reuse objects binding them to different labels
#===============================================================================
# Let's do the same with lists
lst_inst = []
print lst_inst is []
print id(lst_inst), 'vs.', id([])
# What!? Let's try again with bools
bool_inst_1 = True
bool_inst_2 = True
print id(bool_inst_1), 'vs.', id(bool_inst_2)
# Ok. Let's try with other types
none_inst = None
print id(none_inst), 'vs.', id(None)
# 'None' is a constant and is the only accepted value of types.NoneType
list_inst_1 = []
list_inst_2 = []
print id(list_inst_1), 'vs.', id(list_inst_2)
# Why it does not work with lists?
#===============================================================================
# - Objects whose value can change are said to be mutable
# - dicts, lists
# - Objects whose value is unchangeable once they are created are called immutable
# - numbers, strings, tuples, NoneType
# - Mutable types allow in-place modifications (append in a list, pop in a dictionary...)
# - Immutable types instances may be reused by the interpreter (so their id is the same)
#===============================================================================
# Let's check how immutables are reused
sevens = [7, 7, 7, 7, 7]
print map(id, sevens)
abcds = ["abcd", "abcd", "abcd", "abcd", "abcd"]
print map(id, abcds)
empty_tuples = [(), (), ()]
print map(id, empty_tuples)
empty_lists = [[], [], []]
print map(id, empty_lists)
empty_dicts = [{}, {}, {}]
print map(id, empty_dicts)
seven_tuples = [(7,), (7,), (7,)]
print map(id, seven_tuples)
# Best effort: it is not possible to reuse absolutely everything
# Let's change a string value
str_inst = 'instance value'
print str_inst, '@', id(str_inst)
# Reassign
str_inst = str_inst + ' updated'
print str_inst, '@', id(str_inst)
# Let's change a list content
lst_inst = ['instance', 'value']
print lst_inst, '@', id(lst_inst)
# In-place modification
lst_inst.append('updated')
print lst_inst, '@', id(lst_inst)
# Now let's play with dicts
dict1 = {(1, 2): "1, 2", (3, 4): "3, 4"}
dict2 = {[1, 2]: "1, 2", [3, 4]: "3, 4"}
#===============================================================================
# - Mutable types are not stable, so they can not be hashed
#===============================================================================
#===============================================================================
# WARNING!
# - Mutable and immutable types behavior differences can lead to some common errors!!
# - Though sometimes it is the desired behaviour
#===============================================================================
# Multiple assignment with ints (immutable)
intA = intB = 0
print "intA:", intA, '@', id(intA)
print "intB:", intB, '@', id(intB)
# Let's modify one of the ints
intA += 1
print "intA:", intA, '@', id(intA)
print "intB:", intB, '@', id(intB)
# Notice how we are binding a new value (0 + 1) to the same label (intA)
# Ok. Multiple assignment with lists (mutable)
lstA = lstB = []
print "lstA:", lstA, '@', id(lstA)
print "lstB:", lstB, '@', id(lstB)
# Let's modify (in-place) one of the lists
lstA.extend([1, 2, 3])
# What do you expect to be lstB?
print "lstA:", lstA, '@', id(lstA)
print "lstB:", lstB, '@', id(lstB)
#===============================================================================
# Mutable and immutable types common errors:
#
# - Multiple assignments
#===============================================================================
# Name binding or shallow copy with immutables might lead to error too
initial_list = [2, 3, 5]
new_list = initial_list
for idx in range(len(new_list)):
new_list[idx] = new_list[idx] ** 2
print "new_list:", new_list
# What do you expect to be initial_list?
print "initial_list:", initial_list
# And the same happens with constructor by copy
initial_dict = {"ones": [1, 1, 1], "twos": [2, 2, 2]}
upper_dict = dict(initial_dict)
for key in upper_dict:
upper_dict[key.upper()] = upper_dict.pop(key)
print "upper_dict:", upper_dict
# What do you expect to be initial_dict?
print "initial_dict:", initial_dict
# Looks good
upper_dict["TWOS"].append(7)
# And now?
print "initial_dict:", initial_dict
#===============================================================================
# Mutable and immutable types common errors:
#
# - Multiple assignments
# - The same applies with shallow copy or constructor by copy
#===============================================================================
# Use of mutable types as class attributes
class MutablesClass(object):
list_inst = []
int_inst = 0
# Let's instantiate the class twice
inst_A = MutablesClass()
inst_B = MutablesClass()
# Let's change one of the instances
inst_A.int_inst += 1
inst_A.list_inst.extend([5, 7, 9])
print "inst_A.int_inst:", inst_A.int_inst
print "inst_A.list_inst:", inst_A.list_inst
# What do you expect to have inst_B?
print "inst_B.int_inst:", inst_B.int_inst
print "inst_B.list_inst:", inst_B.list_inst
print inst_A.list_inst is inst_B.list_inst
print MutablesClass.list_inst
# Class arguments are stored in the class and created on import time
#===============================================================================
# Mutable and immutable types common errors:
#
# - Multiple assignment
# - The same applies with shallow copy or constructor by copy
#
# - Class attributes
#===============================================================================
# Let's implement a function to add the power of a number to a list
def add_power_to_list(item, powers_lst=[]):
powers_lst.append(item ** 2)
return powers_lst
# Let's call this function
result1 = add_power_to_list(2)
print result1
# Let's call the function again with a different argument
result2 = add_power_to_list(3)
# What do you expect to be result2?
print result1, 'vs', result2
print result1 is result2
print add_power_to_list.func_defaults
# Functions default values are stored in the function object and created on import time
#===============================================================================
# Mutable and immutable types common errors:
#
# - Multiple assignment
# - The same applies with shallow copy or constructor by copy
#
# - Class attributes
#
# - Functions arguments default value
#===============================================================================
# Let's create a function which returns the middle value of a list
def get_middle_item(input_lst):
return input_lst.pop(len(input_lst) / 2)
# Let's call this function
input_lst = range(1, 6)
print input_lst
print get_middle_item(input_lst)
# What do you expect to be input_lst?
print input_lst
#===============================================================================
# Mutable and immutable types common errors:
#
# - Multiple assignment
# - The same applies with shallow copy or constructor by copy
#
# - Class attributes
#
# - Functions arguments default value
#
# - In-place modification of function's mutable arguments
#===============================================================================
##===============================================================================
##===============================================================================
## TIME TO START WORKING!
##
## EXERCISE 1:
## - Solve common mutable / immutable types usage errors
##
## INSTRUCTIONS:
## - Go to exercises/exercise_1 and edit exercise_1.py
## - Change the functions and class implementation to let tests_1.py pass
## - Check tests executing 'nosetests -sv'
##===============================================================================
##===============================================================================
# Wrong multiple assignment of mutables
def split_even_odd(numbers):
even = odd = []
for num in numbers:
if num % 2:
odd.append(num)
else:
even.append(num)
return even, odd
print split_even_odd(range(0, 11))
# Solution multiple assignment of mutables: avoid them
def split_even_odd(numbers):
even = []
odd = []
for num in numbers:
if num % 2:
odd.append(num)
else:
even.append(num)
return even, odd
print split_even_odd(range(0, 11))
# Wrong class attributes of mutable type
class NumbersList(object):
even = []
odd = []
def append_number(self, num):
if num % 2:
self.odd.append(num)
else:
self.even.append(num)
num_lst_A = NumbersList()
num_lst_A.append_number(7)
num_lst_B = NumbersList()
print num_lst_B.even, num_lst_B.odd
# Solution mutable as class attribute: instantiate in the __init__
class NumbersList(object):
even = None
odd = None
def __init__(self):
self.even = []
self.odd = []
def append_number(self, num):
if num % 2:
self.odd.append(num)
else:
self.even.append(num)
num_lst_A = NumbersList()
num_lst_A.append_number(7)
num_lst_B = NumbersList()
print "num_lst_B.even:", num_lst_B.even
print "num_lst_B.odd:", num_lst_B.odd
# Wrong mutable as function default value
def update_even_odd(numbers, even=[], odd=[]):
'''Update incoming even and odd numbers lists with corresponding values of numbers iterable
:param numbers: iterable with numbers
:return (even, odd) lists with corresponding values
'''
for num in numbers:
if num % 2:
odd.append(num)
else:
even.append(num)
return even, odd
print update_even_odd(range(0, 11))
print update_even_odd(range(100, 111))
# Solution mutable as function default value: use None as default value and instantiate inside the function
def update_even_odd(numbers, even=None, odd=None):
if even is None:
even = []
if odd is None:
odd = []
for num in numbers:
if num % 2:
odd.append(num)
else:
even.append(num)
return even, odd
print update_even_odd(range(0, 11))
print update_even_odd(range(100, 111))
#===============================================================================
# To sum up, mutable and immutable types common errors and solution:
#
# - Multiple assignment --> Avoid multiple assignment of mutable types
# - The same applies with shallow copy or constructor by copy --> Use copy.deepcopy
#
# - Class attributes --> Instantiate in the __init__
#
# - Functions arguments default value --> Use None as default value and instantiate inside the function
#
# - In-place modification of function's mutable arguments --> Avoid it. Keep in mind what you are doing
#===============================================================================
#===============================================================================
# MORE INFO:
# - http://docs.python.org/2.7/reference/datamodel.html#objects-values-and-types
# - http://docs.python.org/2/reference/executionmodel.html#naming-and-binding
# - http://docs.python.org/2/library/copy.html#copy.deepcopy
# - http://www.pythontutor.com/visualize.html
#===============================================================================