ch11-24: clean up by @eumiro & sync with Atlas
This commit is contained in:
2
13-protocol-abc/double/double_object.py
Normal file
2
13-protocol-abc/double/double_object.py
Normal file
@@ -0,0 +1,2 @@
|
||||
def double(x: object) -> object:
|
||||
return x * 2
|
||||
11
13-protocol-abc/double/double_protocol.py
Normal file
11
13-protocol-abc/double/double_protocol.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from typing import TypeVar, Protocol
|
||||
|
||||
T = TypeVar('T') # <1>
|
||||
|
||||
class Repeatable(Protocol):
|
||||
def __mul__(self: T, repeat_count: int) -> T: ... # <2>
|
||||
|
||||
RT = TypeVar('RT', bound=Repeatable) # <3>
|
||||
|
||||
def double(x: RT) -> RT: # <4>
|
||||
return x * 2
|
||||
6
13-protocol-abc/double/double_sequence.py
Normal file
6
13-protocol-abc/double/double_sequence.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from collections import abc
|
||||
from typing import Any
|
||||
|
||||
def double(x: abc.Sequence) -> Any:
|
||||
return x * 2
|
||||
|
||||
56
13-protocol-abc/double/double_test.py
Normal file
56
13-protocol-abc/double/double_test.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from typing import TYPE_CHECKING
|
||||
import pytest
|
||||
from double_protocol import double
|
||||
|
||||
def test_double_int() -> None:
|
||||
given = 2
|
||||
result = double(given)
|
||||
assert result == given * 2
|
||||
if TYPE_CHECKING:
|
||||
reveal_type(given)
|
||||
reveal_type(result)
|
||||
|
||||
|
||||
def test_double_str() -> None:
|
||||
given = 'A'
|
||||
result = double(given)
|
||||
assert result == given * 2
|
||||
if TYPE_CHECKING:
|
||||
reveal_type(given)
|
||||
reveal_type(result)
|
||||
|
||||
|
||||
def test_double_fraction() -> None:
|
||||
from fractions import Fraction
|
||||
given = Fraction(2, 5)
|
||||
result = double(given)
|
||||
assert result == given * 2
|
||||
if TYPE_CHECKING:
|
||||
reveal_type(given)
|
||||
reveal_type(result)
|
||||
|
||||
|
||||
def test_double_array() -> None:
|
||||
from array import array
|
||||
given = array('d', [1.0, 2.0, 3.14])
|
||||
result = double(given)
|
||||
if TYPE_CHECKING:
|
||||
reveal_type(given)
|
||||
reveal_type(result)
|
||||
|
||||
|
||||
def test_double_nparray() -> None:
|
||||
import numpy as np # type: ignore
|
||||
given = np.array([[1, 2], [3, 4]])
|
||||
result = double(given)
|
||||
comparison = result == given * 2
|
||||
assert comparison.all()
|
||||
if TYPE_CHECKING:
|
||||
reveal_type(given)
|
||||
reveal_type(result)
|
||||
|
||||
|
||||
def test_double_none() -> None:
|
||||
given = None
|
||||
with pytest.raises(TypeError):
|
||||
result = double(given)
|
||||
Reference in New Issue
Block a user