-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscaffold_tutorial.py
More file actions
2044 lines (1799 loc) · 55.2 KB
/
Copy pathscaffold_tutorial.py
File metadata and controls
2044 lines (1799 loc) · 55.2 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from textwrap import dedent, indent
@dataclass(frozen=True)
class Topic:
number: int
group: str
slug: str
title: str
summary: str
simple_code: str
advanced_code: str
expected_output: list[str]
further_study: str | None = None
TOPICS: list[Topic] = [
Topic(
1,
"01_setup_and_runtime",
"python_project_setup_with_uv",
"Python project setup with uv",
"Use `uv` as the Python equivalent of `dotnet new`, `dotnet restore`, and `dotnet run` in one fast workflow.",
"""
commands = ["uv init", "uv sync", "uv run src/csharp_to_python_learning/concepts/.../topic_01_python_project_setup_with_uv.py"]
for command in commands:
print(command)
""",
"""
tooling = {
"dependencies": "uv add requests",
"dev_dependencies": "uv add --dev pytest ruff mypy",
"lock_refresh": "uv sync --upgrade",
}
print(", ".join(f"{k} => {v}" for k, v in tooling.items()))
""",
["uv init", "dependencies => uv add requests"],
),
Topic(
2,
"01_setup_and_runtime",
"python_execution_model",
"Python execution model",
"Python executes modules top-to-bottom and binds names at runtime, then runs guarded script code under `if __name__ == '__main__'`.",
"""
module_name = __name__
print(f"module name: {module_name}")
print("main block runs only when executed as a script")
""",
"""
source = "value = 40 + 2\\nprint('compiled value:', value)"
code_object = compile(source, "<dynamic>", "exec")
exec(code_object)
""",
["module name:", "compiled value: 42"],
),
Topic(
3,
"02_data_and_flow",
"variables_names_references_and_mutability",
"Variables, names, references, and mutability",
"Python names point to objects; assignment rebinds names, while mutating a shared object affects all aliases.",
"""
a = [1, 2]
b = a
b.append(3)
print(a, b)
""",
"""
original = {"region": "APAC", "skills": ["C#", "SQL"]}
copy_for_edit = {**original, "skills": [*original["skills"], "Python"]}
print(original)
print(copy_for_edit)
""",
["[1, 2, 3] [1, 2, 3]", "{'region': 'APAC', 'skills': ['C#', 'SQL']}"],
),
Topic(
4,
"02_data_and_flow",
"primitive_types",
"Primitive types",
"Python has familiar scalar types (`int`, `float`, `bool`, `str`) plus precision types like `Decimal`.",
"""
from decimal import Decimal
amount = Decimal("19.99") * 3
print(type(amount).__name__, amount)
""",
"""
from fractions import Fraction
ratio = Fraction(1, 3) + Fraction(1, 6)
print("fraction:", ratio, "as float:", float(ratio))
""",
["Decimal 59.97", "fraction: 1/2 as float: 0.5"],
),
Topic(
5,
"02_data_and_flow",
"collections",
"Collections: list, tuple, dict, set, frozenset",
"Python collection types have different mutability and lookup guarantees; choosing the right one matters in production code.",
"""
items = ["build", "test", "deploy"]
mapping = {"build": 1, "test": 2}
unique = set(items)
print(items[0], mapping["test"], "deploy" in unique)
""",
"""
permissions = frozenset({"read", "write"})
profile = ("nikhil", "senior", permissions)
print(profile[0], sorted(profile[2]))
""",
["build 2 True", "nikhil ['read', 'write']"],
),
Topic(
6,
"02_data_and_flow",
"slicing_and_unpacking",
"Slicing and unpacking",
"Python slicing and unpacking replace many verbose loop/indexing patterns common in C#.",
"""
numbers = [10, 20, 30, 40, 50]
head, *middle, tail = numbers
print(head, middle, tail)
""",
"""
from itertools import islice
stream = (n * n for n in range(100))
window = list(islice(stream, 5, 10))
print(window)
""",
["10 [20, 30, 40] 50", "[25, 36, 49, 64, 81]"],
),
Topic(
7,
"02_data_and_flow",
"control_flow",
"Control flow",
"Python control flow favors readability with indentation and expressive constructs like `for ... else`.",
"""
for n in range(3):
if n == 1:
continue
print("value", n)
""",
"""
target = 7
for n in [1, 3, 5]:
if n == target:
print("found")
break
else:
print("not found")
""",
["value 0", "not found"],
),
Topic(
8,
"03_functions_and_functional_tools",
"functions",
"Functions",
"Functions are first-class objects in Python, so you can pass and return them directly.",
"""
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3))
""",
"""
def pipeline(value: int, *steps):
result = value
for step in steps:
result = step(result)
return result
print(pipeline(5, lambda x: x + 1, lambda x: x * 3))
""",
["5", "18"],
),
Topic(
9,
"03_functions_and_functional_tools",
"default_and_keyword_only_arguments",
"Default arguments and keyword-only arguments",
"Keyword-only arguments let you model explicit APIs like named optional parameters in C#.",
"""
def greet(name: str, *, excited: bool = False) -> str:
return f"Hello {name}{'!' if excited else '.'}"
print(greet("Nikhil", excited=True))
""",
"""
def append_item(value: int, bucket: list[int] | None = None) -> list[int]:
bucket = bucket or []
bucket.append(value)
return bucket
print(append_item(1), append_item(2))
""",
["Hello Nikhil!", "[1] [2]"],
),
Topic(
10,
"03_functions_and_functional_tools",
"lambdas",
"Lambdas",
"Python lambdas are small expression-only functions, best used inline for short transformations.",
"""
teams = ["platform", "api", "ml"]
print(sorted(teams, key=lambda t: len(t)))
""",
"""
records = [{"name": "A", "score": 92}, {"name": "B", "score": 81}]
top = max(records, key=lambda r: (r["score"], r["name"]))
print(top["name"], top["score"])
""",
["['ml', 'api', 'platform']", "A 92"],
),
Topic(
11,
"03_functions_and_functional_tools",
"closures",
"Closures",
"Closures capture surrounding state, similar to C# captured variables in local functions/lambdas.",
"""
def make_counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
counter = make_counter()
print(counter(), counter())
""",
"""
def memoized_square():
cache: dict[int, int] = {}
def run(value: int) -> int:
if value not in cache:
cache[value] = value * value
return cache[value]
return run
square = memoized_square()
print(square(12), square(12))
""",
["1 2", "144 144"],
),
Topic(
12,
"03_functions_and_functional_tools",
"decorators",
"Decorators",
"Decorators provide AOP-style wrappers for logging, validation, authorization, and instrumentation.",
"""
from functools import wraps
def tagged(tag: str):
def deco(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"[{tag}] start")
return func(*args, **kwargs)
return wrapper
return deco
@tagged("demo")
def run():
print("work")
run()
""",
"""
import time
def timed(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"elapsed={time.perf_counter() - start:.6f}")
return result
return wrapper
@timed
def compute():
return sum(range(10_000))
print(compute())
""",
["[demo] start", "elapsed="],
),
Topic(
13,
"03_functions_and_functional_tools",
"comprehensions",
"Comprehensions",
"Comprehensions replace many LINQ `Select`/`Where` one-liners while staying explicit and Pythonic.",
"""
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers if n % 2 == 1]
print(squares)
""",
"""
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [cell for row in matrix for cell in row]
lookup = {value: value * value for value in flat}
print(flat, lookup[6])
""",
["[1, 9, 25]", "[1, 2, 3, 4, 5, 6] 36"],
),
Topic(
14,
"03_functions_and_functional_tools",
"iterators_and_generators",
"Iterators and generators",
"Generators are lazy and memory-efficient, which is crucial for streaming and ETL workloads.",
"""
def count_up(limit: int):
current = 0
while current < limit:
yield current
current += 1
print(list(count_up(4)))
""",
"""
def lines():
yield "alpha"
yield "beta"
def upper(values):
for value in values:
yield value.upper()
print(list(upper(lines())))
""",
["[0, 1, 2, 3]", "['ALPHA', 'BETA']"],
),
Topic(
15,
"03_functions_and_functional_tools",
"context_managers",
"Context managers",
"Context managers are deterministic resource guards; think `using` blocks generalized for any enter/exit behavior.",
"""
from contextlib import contextmanager
@contextmanager
def labelled(name: str):
print(f"enter {name}")
try:
yield
finally:
print(f"exit {name}")
with labelled("demo"):
print("inside")
""",
"""
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "note.txt"
path.write_text("safe write", encoding="utf-8")
print(path.read_text(encoding="utf-8"))
""",
["enter demo", "safe write"],
),
Topic(
16,
"04_errors_and_modules",
"exceptions",
"Exceptions",
"Python exceptions are value-carrying objects; use narrow catches and explicit re-raising for clarity.",
"""
try:
int("not-a-number")
except ValueError as exc:
print(type(exc).__name__)
finally:
print("cleanup")
""",
"""
class DomainError(RuntimeError):
pass
def parse_port(raw: str) -> int:
try:
value = int(raw)
except ValueError as exc:
raise DomainError("invalid port") from exc
return value
try:
parse_port("abc")
except DomainError as exc:
print(exc)
""",
["ValueError", "invalid port"],
),
Topic(
17,
"04_errors_and_modules",
"modules_and_packages",
"Modules and packages",
"A Python package is a directory namespace, similar to assemblies + namespaces but resolved at runtime.",
"""
import json
payload = json.loads('{"status":"ok"}')
print(payload["status"])
""",
"""
import importlib
module = importlib.import_module("statistics")
print(module.mean([2, 4, 8]))
""",
["ok", "4.666"],
),
Topic(
18,
"04_errors_and_modules",
"imports_and_import_system",
"Imports and import system",
"Imports are executable statements with caching in `sys.modules`; import style affects startup and clarity.",
"""
import importlib.util
spec = importlib.util.find_spec("pathlib")
print(spec is not None)
""",
"""
def lazy_json():
import json
return json.dumps({"lazy": True})
print(lazy_json())
""",
["True", '{"lazy": true}'],
),
Topic(
19,
"05_oop_and_modeling",
"object_oriented_programming",
"Object-oriented programming",
"Python supports classic OOP, but with less ceremony and more runtime flexibility than C#.",
"""
class Account:
def __init__(self, owner: str):
self.owner = owner
self.balance = 0
def deposit(self, amount: int) -> None:
self.balance += amount
a = Account("Nikhil")
a.deposit(50)
print(a.owner, a.balance)
""",
"""
from dataclasses import dataclass
@dataclass
class TaxedAmount:
net: float
tax_rate: float
@property
def gross(self) -> float:
return self.net * (1 + self.tax_rate)
print(round(TaxedAmount(100, 0.18).gross, 2))
""",
["Nikhil 50", "118.0"],
),
Topic(
20,
"05_oop_and_modeling",
"inheritance_and_composition",
"Inheritance and composition",
"Prefer composition when behavior should vary at runtime; use inheritance for stable hierarchies.",
"""
class Animal:
def speak(self) -> str:
return "..."
class Dog(Animal):
def speak(self) -> str:
return "woof"
print(Dog().speak())
""",
"""
class EmailSender:
def send(self, message: str) -> str:
return f"email:{message}"
class Notifier:
def __init__(self, sender):
self.sender = sender
def notify(self, message: str) -> str:
return self.sender.send(message)
print(Notifier(EmailSender()).notify("deployed"))
""",
["woof", "email:deployed"],
),
Topic(
21,
"05_oop_and_modeling",
"properties",
"Properties",
"Properties keep attribute syntax while enforcing invariants, similar to C# `get`/`set` properties.",
"""
class Temperature:
def __init__(self):
self._celsius = 0.0
@property
def celsius(self) -> float:
return self._celsius
@celsius.setter
def celsius(self, value: float) -> None:
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
t = Temperature()
t.celsius = 22.5
print(t.celsius)
""",
"""
from functools import cached_property
class Report:
def __init__(self, values: list[int]):
self.values = values
@cached_property
def total(self) -> int:
print("computing")
return sum(self.values)
r = Report([1, 2, 3])
print(r.total, r.total)
""",
["22.5", "computing"],
),
Topic(
22,
"05_oop_and_modeling",
"dataclasses",
"Dataclasses",
"Dataclasses are concise record-like types with optional immutability, ordering, and slots.",
"""
from dataclasses import dataclass
@dataclass
class User:
id: int
name: str
print(User(1, "Nikhil"))
""",
"""
from dataclasses import dataclass, field
@dataclass(frozen=True, order=True, slots=True)
class Job:
priority: int
name: str
tags: tuple[str, ...] = field(default_factory=tuple)
print(sorted([Job(2, "test"), Job(1, "build")])[0].name)
""",
["User(id=1, name='Nikhil')", "build"],
),
Topic(
23,
"05_oop_and_modeling",
"enums",
"Enums",
"Enums model closed sets of values and avoid stringly-typed logic in business rules.",
"""
from enum import Enum, auto
class Status(Enum):
PENDING = auto()
DONE = auto()
print(Status.DONE.name)
""",
"""
from enum import StrEnum
class Environment(StrEnum):
DEV = "dev"
PROD = "prod"
print(Environment.PROD.upper())
""",
["DONE", "PROD"],
),
Topic(
24,
"06_typing_and_protocols",
"protocols_and_structural_typing",
"Protocols and structural typing",
"Protocols model behavior contracts by shape (duck typing) instead of explicit inheritance.",
"""
from typing import Protocol
class Runner(Protocol):
def run(self) -> str: ...
class Job:
def run(self) -> str:
return "ok"
def execute(target: Runner) -> str:
return target.run()
print(execute(Job()))
""",
"""
from typing import Protocol, TypeVar
T = TypeVar("T")
class Serializer(Protocol[T]):
def serialize(self, value: T) -> str: ...
class IntSerializer:
def serialize(self, value: int) -> str:
return str(value)
print(IntSerializer().serialize(42))
""",
["ok", "42"],
),
Topic(
25,
"05_oop_and_modeling",
"abstract_base_classes",
"Abstract base classes",
"ABCs define explicit contracts and can also provide reusable default behavior.",
"""
from abc import ABC, abstractmethod
class Repository(ABC):
@abstractmethod
def get(self, key: str) -> str: ...
class InMemoryRepository(Repository):
def get(self, key: str) -> str:
return f"value:{key}"
print(InMemoryRepository().get("x"))
""",
"""
from collections.abc import Iterable
class CsvLike:
def __iter__(self):
yield from ["a,b", "c,d"]
print(isinstance(CsvLike(), Iterable))
""",
["value:x", "True"],
),
Topic(
26,
"06_typing_and_protocols",
"type_hints",
"Type hints",
"Type hints improve readability and tooling without changing runtime behavior.",
"""
def normalize(names: list[str]) -> list[str]:
return [name.strip().title() for name in names]
print(normalize([" nikhil", "PRIYA "]))
""",
"""
from typing import TypedDict
class Config(TypedDict):
retries: int
timeout: float
config: Config = {"retries": 3, "timeout": 1.5}
print(config["retries"])
""",
["['Nikhil', 'Priya']", "3"],
),
Topic(
27,
"06_typing_and_protocols",
"generics",
"Generics",
"Python generics are type-checker friendly and map closely to C# generic classes and methods.",
"""
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
print(Box[int](10).value)
""",
"""
from typing import TypeVar
U = TypeVar("U")
def first(items: list[U]) -> U:
return items[0]
print(first(["a", "b", "c"]))
""",
["10", "a"],
),
Topic(
28,
"07_advanced_language_runtime",
"pattern_matching",
"Pattern matching",
"Structural pattern matching is Python's expressive branching feature for tuple/list/dict/object shapes.",
"""
def classify(value):
match value:
case 0:
return "zero"
case int() as n if n > 0:
return "positive"
case _:
return "other"
print(classify(3))
""",
"""
from dataclasses import dataclass
@dataclass
class Event:
kind: str
size: int
def route(event: Event) -> str:
match event:
case Event(kind="upload", size=size) if size > 10:
return "large-upload"
case Event(kind="upload"):
return "small-upload"
case _:
return "other"
print(route(Event("upload", 12)))
""",
["positive", "large-upload"],
),
Topic(
29,
"07_advanced_language_runtime",
"dunder_methods_and_data_model",
"Dunder methods and Python data model",
"Python objects participate in language syntax by implementing special (dunder) methods.",
"""
class Team:
def __init__(self, members):
self.members = members
def __len__(self):
return len(self.members)
print(len(Team(['a', 'b', 'c'])))
""",
"""
class Vector:
def __init__(self, x: int, y: int):
self.x, self.y = x, y
def __add__(self, other: "Vector") -> "Vector":
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self) -> str:
return f"Vector({self.x}, {self.y})"
print(Vector(1, 2) + Vector(3, 4))
""",
["3", "Vector(4, 6)"],
),
Topic(
30,
"07_advanced_language_runtime",
"descriptors",
"Descriptors",
"Descriptors power `property`, ORM fields, and validation by intercepting attribute access at class level.",
"""
class Positive:
def __set_name__(self, owner, name):
self.private_name = f"_{name}"
def __get__(self, obj, objtype=None):
return getattr(obj, self.private_name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError("must be positive")
setattr(obj, self.private_name, value)
class Order:
quantity = Positive()
o = Order()
o.quantity = 5
print(o.quantity)
""",
"""
class Tracked:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
value = obj.__dict__[self.name]
print(f"read {self.name}={value}")
return value
def __set__(self, obj, value):
obj.__dict__[self.name] = value
class Profile:
level = Tracked()
p = Profile()
p.level = "senior"
print(p.level)
""",
["5", "read level=senior"],
),
Topic(
31,
"07_advanced_language_runtime",
"metaclasses",
"Metaclasses",
"Metaclasses customize class creation and are useful for registries and framework hooks.",
"""
class AddVersion(type):
def __new__(mcls, name, bases, namespace):
namespace["version"] = "1.0"
return super().__new__(mcls, name, bases, namespace)
class Service(metaclass=AddVersion):
pass
print(Service.version)
""",
"""
class RegistryMeta(type):
registry: dict[str, type] = {}
def __new__(mcls, name, bases, namespace):
cls = super().__new__(mcls, name, bases, namespace)
if name != "BasePlugin":
mcls.registry[name] = cls
return cls
class BasePlugin(metaclass=RegistryMeta):
pass
class CsvPlugin(BasePlugin):
pass
print(sorted(RegistryMeta.registry))
""",
["1.0", "['CsvPlugin']"],
),
Topic(
32,
"08_concurrency_and_systems",
"async_and_await",
"Async and await",
"Async functions represent suspendable workflows; use them for I/O concurrency, not CPU parallelism.",
"""
import asyncio
async def work():
await asyncio.sleep(0)
return "done"
print(asyncio.run(work()))
""",
"""
import asyncio
async def fetch(label: str, delay: float):
await asyncio.sleep(delay)
return label
async def main_async():
result = await asyncio.gather(fetch("a", 0.01), fetch("b", 0.01))
print(result)
asyncio.run(main_async())
""",
["done", "['a', 'b']"],
),
Topic(
33,
"08_concurrency_and_systems",
"asyncio_tasks_queues_cancellation_timeouts",
"asyncio tasks, queues, cancellation, timeouts",
"Production asyncio code needs task orchestration, cancellation handling, queues, and timeout guards.",
"""
import asyncio
async def producer(queue: asyncio.Queue[int]) -> None:
for value in [1, 2, 3]:
await queue.put(value)
await queue.put(-1)
async def consumer(queue: asyncio.Queue[int]) -> None:
while True:
item = await queue.get()
if item == -1:
break
print("consumed", item)
async def main_async():
q: asyncio.Queue[int] = asyncio.Queue()
await asyncio.gather(producer(q), consumer(q))
asyncio.run(main_async())
""",
"""
import asyncio
async def slow():
await asyncio.sleep(0.2)
return "slow"
async def main_async():
try:
await asyncio.wait_for(slow(), timeout=0.05)
except TimeoutError:
print("timed out")
asyncio.run(main_async())
""",
["consumed 1", "timed out"],
),
Topic(
34,
"08_concurrency_and_systems",
"threading",
"Threading",
"Threading works well for blocking I/O integration, protected with locks for shared mutable state.",
"""
import threading
counter = 0
lock = threading.Lock()
def inc():
global counter
for _ in range(1000):
with lock:
counter += 1
t1 = threading.Thread(target=inc)
t2 = threading.Thread(target=inc)
t1.start(); t2.start()
t1.join(); t2.join()
print(counter)
""",
"""
from concurrent.futures import ThreadPoolExecutor
def upper(text: str) -> str:
return text.upper()
with ThreadPoolExecutor(max_workers=2) as pool:
print(list(pool.map(upper, ["a", "b", "c"])))
""",
["2000", "['A', 'B', 'C']"],
),
Topic(
35,
"08_concurrency_and_systems",
"multiprocessing",
"Multiprocessing",
"Use multiprocessing for CPU-bound work when threads are limited by interpreter-level contention.",
"""