|
6 | 6 |
|
7 | 7 | # Simple example: Concrete types |
8 | 8 | def add_one(number: int) -> int: |
| 9 | + """ |
| 10 | + Add 1 to an `int`, returning the sum. |
| 11 | +
|
| 12 | + >>> add_one(9) |
| 13 | + 10 |
| 14 | + >>> add_one(-11) |
| 15 | + -10 |
| 16 | + >>> add_one(2**63-1) |
| 17 | + 9223372036854775808 |
| 18 | + """ |
9 | 19 | return number + 1 |
10 | 20 |
|
11 | 21 |
|
12 | 22 | # Union types. |
13 | 23 | # Optional[T] == Union[T, None] |
14 | 24 | def reciprocal(number: Union[int, float]) -> Optional[float]: |
| 25 | + """ |
| 26 | + Return the reciprocal of the given number. If the number is zero, return `None`. |
| 27 | +
|
| 28 | + >>> reciprocal(5) |
| 29 | + 0.2 |
| 30 | + >>> reciprocal(-20) |
| 31 | + -0.05 |
| 32 | + >>> reciprocal(-0.0) # returns None |
| 33 | + """ |
15 | 34 | if number == 0: |
16 | 35 | return None |
17 | 36 | return 1 / number |
18 | 37 |
|
19 | 38 |
|
20 | 39 | # Abstract types |
21 | 40 | def flatten_ints(its: Iterable[Iterable[int]]) -> Iterable[int]: |
| 41 | + """ |
| 42 | + Given an iterable of iterables of ints, return an iterable of all the ints |
| 43 | + in the inner iterables. |
| 44 | +
|
| 45 | + >>> list(flatten_ints([[9, 11], [12], [4, 5]])) |
| 46 | + [9, 11, 12, 4, 5] |
| 47 | + >>> list(flatten_ints([[], (), set()])) |
| 48 | + [] |
| 49 | + """ |
22 | 50 | for it in its: |
23 | 51 | for i in it: |
24 | 52 | yield i |
25 | 53 |
|
26 | 54 |
|
27 | 55 | # Types generic over a TypeVar |
28 | 56 | def flatten_generic(its: Iterable[Iterable[T]]) -> Iterable[T]: |
| 57 | + """ |
| 58 | + Given an iterable of iterables, return an iterable of all the inner |
| 59 | + elements in the inner iterables. |
| 60 | +
|
| 61 | + >>> list(flatten_ints(["hi", (4, 2.54)])) |
| 62 | + ['h', 'i', 4, 2.54] |
| 63 | + """ |
29 | 64 | for it in its: |
30 | 65 | for i in it: |
31 | 66 | yield i |
32 | 67 |
|
33 | 68 |
|
34 | 69 | class Circle: |
| 70 | + """ |
| 71 | + Circle(radius) -> Self |
| 72 | +
|
| 73 | + A `Circle` represents the abstract geometric shape. |
| 74 | +
|
| 75 | + >>> c = Circle(2.21); c.diameter |
| 76 | + 4.42 |
| 77 | + >>> c2 = Circle.from_circumference(100); round(c2.radius, 3) |
| 78 | + 15.916 |
| 79 | + """ |
| 80 | + |
35 | 81 | PI = 3.14159 |
| 82 | + |
36 | 83 | __slots__ = ["radius"] |
37 | 84 |
|
38 | 85 | def __init__(self, radius: Union[int, float]): |
|
0 commit comments