Skip to content

Commit 7162643

Browse files
committed
mymax: step 01, misstep
1 parent 44c97c7 commit 7162643

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
Q: Why not define ``Number`` as follows?
3+
4+
::
5+
Number = Union[float, Decimal, Fraction]
6+
7+
8+
A: Because ``Union`` is not helpful as a return type.
9+
10+
"Be conservative in what you send, be liberal in what you accept."
11+
—Postel's Law
12+
13+
"""
14+
15+
from decimal import Decimal
16+
from fractions import Fraction
17+
from typing import Union
18+
19+
Number = Union[float, Decimal, Fraction]
20+
21+
22+
def max(a: Number, b: Number) -> Number:
23+
return a if a >= b else b
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from decimal import Decimal
2+
from fractions import Fraction
3+
4+
import mymax
5+
from mymax import Number
6+
7+
import pytest
8+
9+
10+
@pytest.mark.parametrize(
11+
'a, b, expected',
12+
[
13+
(1, 2, 2),
14+
(-3, -1, -1),
15+
(4, 4, 4),
16+
],
17+
)
18+
def test_two_ints(a: int, b: int, expected: int) -> None:
19+
result = mymax.max(a, b)
20+
assert result == expected
21+
22+
23+
def test_two_numbers() -> None:
24+
result = mymax.max(Fraction(1, 3), Fraction(1, 4))
25+
assert result == Fraction(1, 3)
26+
27+
28+
@pytest.mark.parametrize(
29+
'a, b, expected',
30+
[
31+
(1, 2, 2),
32+
(0.1, 0.01, 0.1),
33+
(Fraction(1, 3), Fraction(1, 2), Fraction(1, 2)),
34+
(Decimal('-1.3'), Decimal('-1.2'), Decimal('-1.2')),
35+
],
36+
)
37+
def test_two_numbers_params(a: Number, b: Number, expected: Number) -> None:
38+
result = mymax.max(a, b)
39+
assert result == expected
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[mypy]
2+
python_version = 3.9
3+
warn_unused_configs = True
4+
disallow_incomplete_defs = True
5+
[mypy-pytest]
6+
ignore_missing_imports = True

0 commit comments

Comments
 (0)