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
75 lines (51 loc) · 1.31 KB
/
Copy pathtemplate.py
File metadata and controls
75 lines (51 loc) · 1.31 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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
An example of the Template pattern in Python
*TL;DR
Defines the skeleton of a base algorithm, deferring definition of exact
steps to subclasses.
*Examples in Python ecosystem:
Django class based views: https://docs.djangoproject.com/en/2.1/topics/class-based-views/
"""
defget_text():
return"plain-text"
defget_pdf():
return"pdf"
defget_csv():
return"csv"
defconvert_to_text(data):
print("[CONVERT]")
return"{} as text".format(data)
defsaver():
print("[SAVE]")
deftemplate_function(getter, converter=False, to_save=False):
data=getter()
print("Got `{}`".format(data))
iflen(data) <=3andconverter:
data=converter(data)
else:
print("Skip conversion")
ifto_save:
saver()
print("`{}` was processed".format(data))
defmain():
"""
>>> template_function(get_text, to_save=True)
Got `plain-text`
Skip conversion
[SAVE]
`plain-text` was processed
>>> template_function(get_pdf, converter=convert_to_text)
Got `pdf`
[CONVERT]
`pdf as text` was processed
>>> template_function(get_csv, to_save=True)
Got `csv`
Skip conversion
[SAVE]
`csv` was processed
"""
if__name__=="__main__":
importdoctest
doctest.testmod()