-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_dependency_injection.py
More file actions
53 lines (33 loc) · 1.06 KB
/
Copy pathexample_dependency_injection.py
File metadata and controls
53 lines (33 loc) · 1.06 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
"""
https://python-dependency-injector.ets-labs.org/introduction/di_in_python.html
"""
### before
import os
class ApiClient:
def __init__(self):
self.api_key = os.getenv("API_KEY") # <-- dependency
self.timeout = os.getenv("TIMEOUT") # <-- dependency
class Service:
def __init__(self):
self.api_client = ApiClient() # <-- dependency
def main() -> None:
service = Service() # <-- dependency
...
if __name__ == "__main__":
main()
### after
import os
class ApiClient:
def __init__(self, api_key:str, timeout: int):
self.api_key = api_key # <-- dependency injected
self.timeout = timeout # <-- dependency injected
class Service:
def __init__(self , api_client: ApiClient): # <-- dependency injected
self.api_client = api_client # <-- dependency injected
def main(service: Service) -> None: # <-- dependency injected
pass
if __name__=="__main__":
main(Service(ApiClient(
api_key=os.getenv("API_KEY"),
timeout=os.getenv("TIMEOUT")
)))