Skip to content

Commit 00fd985

Browse files
Lambda in a loop vid
1 parent 962f24a commit 00fd985

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ James and his team are available for consulting, contracting, code reviews, and
1212

1313
| N | Code | Video |
1414
|-----| --- |--- |
15+
| 129 | [src](videos/129_lambda_in_a_loop_is_a_code_smell) | [Lambda in a Loop is a Code Smell](https://youtu.be/fZE6ZWde-Os) |
1516
| 128 | [src](videos/128_id_mapping) | [A forbidden Python technique to put ANYTHING in a dict or set.](https://youtu.be/NpdNDTncxwA) |
1617
| 127 | [src](videos/127_accidentally_quadratic_unique_sum) | [Don't make this big O mistake!](https://youtu.be/PXWL_Xzyrp4) |
1718
| 126 | [src](videos/126_attrs_revolution) | [Why I prefer attrs over dataclasses](https://youtu.be/1S2h11XronA) |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import functools
2+
import threading
3+
import time
4+
from collections.abc import Callable
5+
from concurrent.futures import ThreadPoolExecutor, Future
6+
7+
io_lock = threading.Lock()
8+
9+
10+
def print_ts(*args):
11+
with io_lock:
12+
print(*args)
13+
14+
15+
def print_task_completed(future: Future, task_id: str):
16+
if future.exception() is None:
17+
print_ts(f"completed")
18+
else:
19+
print_ts(f"completed with error")
20+
21+
22+
def dispatch_work(work: list[tuple[str, Callable]]):
23+
with ThreadPoolExecutor(max_workers=4) as executor:
24+
for task_id, func in work:
25+
future = executor.submit(func)
26+
future.add_done_callback(
27+
functools.partial(print_task_completed, task_id=task_id)
28+
)
29+
# future.add_done_callback(
30+
# lambda fut: print_task_completed(fut, task_id)
31+
# )
32+
33+
34+
def some_work(arg):
35+
time.sleep(0.0) # simulate work
36+
print_ts(arg)
37+
38+
39+
def main():
40+
work = [
41+
("task_a", functools.partial(some_work, "A")),
42+
("task_b", functools.partial(some_work, "B")),
43+
("task_c", functools.partial(some_work, "C")),
44+
("task_d", functools.partial(some_work, "D")),
45+
]
46+
dispatch_work(work)
47+
print("all done")
48+
49+
50+
if __name__ == '__main__':
51+
main()

0 commit comments

Comments
 (0)