- Notifications
You must be signed in to change notification settings - Fork 7k
/
Copy pathtemplate.py
73 lines (49 loc) · 1.29 KB
/
template.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
"""
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() ->str:
return"plain-text"
defget_pdf() ->str:
return"pdf"
defget_csv() ->str:
return"csv"
defconvert_to_text(data: str) ->str:
print("[CONVERT]")
returnf"{data} as text"
defsaver() ->None:
print("[SAVE]")
deftemplate_function(getter, converter=False, to_save=False) ->None:
data=getter()
print(f"Got `{data}`")
iflen(data) <=3andconverter:
data=converter(data)
else:
print("Skip conversion")
ifto_save:
saver()
print(f"`{data}` was processed")
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()