-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
52 lines (45 loc) · 1.36 KB
/
Copy pathexample.py
File metadata and controls
52 lines (45 loc) · 1.36 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
# example.py — Batch 12
# --- 1. *args unpacking in calls ---
def add3(a: int, b: int, c: int) -> int:
return a + b + c
def test_star_unpack() -> int:
nums: list[int] = [10, 20, 30]
return add3(*nums) # 60
# --- 2. *args partial unpack f(x, *lst) ---
def test_star_partial() -> int:
rest: list[int] = [2, 3]
return add3(1, *rest) # 6
# --- 3. __iter__ / __next__ user iterator ---
class Range:
cur: int
stop: int
def __init__(self, stop: int) -> None:
self.cur = 0
self.stop = stop
def __iter__(self) -> "Range":
return self
def __next__(self) -> int:
if self.cur >= self.stop:
raise StopIteration()
self.cur = self.cur + 1
return self.cur
def test_user_iter() -> int:
total: int = 0
for x in Range(5):
total = total + x
return total # 1+2+3+4+5 = 15
# --- 4. raise / catch StopIteration ---
def test_stop_iteration() -> int:
r: Range = Range(2)
a: int = r.__next__() # 1
b: int = r.__next__() # 2
try:
r.__next__() # raises StopIteration
except StopIteration:
return a + b # 3
return 0
if __name__ == "__main__":
print("star_unpack:", test_star_unpack())
print("star_partial:", test_star_partial())
print("user_iter:", test_user_iter())
print("stop_iteration:", test_stop_iteration())