-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitem_15.py
executable file
·96 lines (73 loc) · 2.24 KB
/
item_15.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
#!/usr/bin/env python3
'''Item 15 from Effective Python'''
# Example 1
''' A common way to do this is to pass a helper function as the key argument to
a list's sort method. The helper's return value will be used as the value for
sorting each item in the list '''
print('Example 1:\n==========')
def sort_priority(values, group):
def helper(x):
if x in group:
return (0, x)
return (1, x)
values.sort(key=helper)
# Example 2
''' That function works for simple inputs '''
print('\nExample 2:\n==========')
numbers = [8, 3, 1, 2, 5, 4, 7, 6]
group = {2, 3, 5, 7}
sort_priority(numbers, group)
print(numbers)
# Example 3
''' Why not also use the closure to flip a flag when high-priority items are
seen? Then the function can return the flag value after it's been modified by
the closure '''
print('\nExample 3:\n==========')
def sort_priority2(numbers, group):
found = False
def helper(x):
if x in group:
found = True # Seems simple
return (0, x)
return (1, x)
numbers.sort(key=helper)
return found
# Example 4
''' run the function on the same inputs as before '''
print('\nExample 4:\n==========')
found = sort_priority2(numbers, group)
print('Found:', found)
print(numbers)
# Example 5
''' The nonlocal statement is used to indicate that scope traversal should
happen upon assignment for a specific variable name '''
print('\nExample 5:\n==========')
def sort_priority3(numbers, group):
found = False
def helper(x):
nonlocal found
if x in group:
found = True
return (0, x)
return (1, x)
numbers.sort(key=helper)
return found
# Example 6
''' When your usage of nonlocal starts getting complicated, it's better to wrap
your state in a helper class. Here, I define a class that achieves the same
result as the nonlocal approach '''
print('\nExample 6:\n==========')
class Sorter(object):
def __init__(self, group):
self.group = group
self.found = False
def __call__(self, x):
if x in self.group:
self.found = True
return (0, x)
return (1, x)
sorter = Sorter(group)
numbers.sort(key=sorter)
assert sorter.found is True
print('Found:', found)
print(numbers)