forked from faif/python-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.py
More file actions
Latest commit
50 lines (39 loc) · 1.35 KB
/
Copy pathtemplate.py
File metadata and controls
50 lines (39 loc) · 1.35 KB
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
'''http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/'''
"""An example of the Template pattern in Python"""
ingredients="spam eggs apple"
line='-'*10
# Skeletons
defiter_elements(getter, action):
"""Template skeleton that iterates items"""
forelementingetter():
action(element)
print(line)
defrev_elements(getter, action):
"""Template skeleton that iterates items in reverse order"""
forelementingetter()[::-1]:
action(element)
print(line)
# Getters
defget_list():
returningredients.split()
defget_lists():
return [list(x) forxiningredients.split()]
# Actions
defprint_item(item):
print(item)
defreverse_item(item):
print(item[::-1])
# Makes templates
defmake_template(skeleton, getter, action):
"""Instantiate a template method with getter and action"""
deftemplate():
skeleton(getter, action)
returntemplate
# Create our template functions
templates= [make_template(s, g, a)
forgin (get_list, get_lists)
forain (print_item, reverse_item)
forsin (iter_elements, rev_elements)]
# Execute them
fortemplateintemplates:
template()