forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.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/
"""
def get_text() -> str:
return "plain-text"
def get_pdf() -> str:
return "pdf"
def get_csv() -> str:
return "csv"
def convert_to_text(data: str) -> str:
print("[CONVERT]")
return f"{data} as text"
def saver() -> None:
print("[SAVE]")
def template_function(getter, converter=False, to_save=False) -> None:
data = getter()
print(f"Got `{data}`")
if len(data) <= 3 and converter:
data = converter(data)
else:
print("Skip conversion")
if to_save:
saver()
print(f"`{data}` was processed")
def main():
"""
>>> 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__":
import doctest
doctest.testmod()