ch11-24: clean up by @eumiro & sync with Atlas
This commit is contained in:
5
13-protocol-abc/typing/randompick.py
Normal file
5
13-protocol-abc/typing/randompick.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from typing import Protocol, runtime_checkable, Any
|
||||
|
||||
@runtime_checkable
|
||||
class RandomPicker(Protocol):
|
||||
def pick(self) -> Any: ...
|
||||
25
13-protocol-abc/typing/randompick_test.py
Normal file
25
13-protocol-abc/typing/randompick_test.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import random
|
||||
from typing import Any, Iterable, TYPE_CHECKING
|
||||
|
||||
from randompick import RandomPicker # <1>
|
||||
|
||||
class SimplePicker(): # <2>
|
||||
def __init__(self, items: Iterable) -> None:
|
||||
self._items = list(items)
|
||||
random.shuffle(self._items)
|
||||
|
||||
def pick(self) -> Any: # <3>
|
||||
return self._items.pop()
|
||||
|
||||
def test_isinstance() -> None: # <4>
|
||||
popper = SimplePicker([1])
|
||||
assert isinstance(popper, RandomPicker)
|
||||
|
||||
def test_item_type() -> None: # <5>
|
||||
items = [1, 2]
|
||||
popper = SimplePicker(items)
|
||||
item = popper.pick()
|
||||
assert item in items
|
||||
if TYPE_CHECKING:
|
||||
reveal_type(item) # <6>
|
||||
assert isinstance(item, int)
|
||||
6
13-protocol-abc/typing/randompickload.py
Normal file
6
13-protocol-abc/typing/randompickload.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from typing import Protocol, runtime_checkable, Any, Iterable
|
||||
from randompick import RandomPicker
|
||||
|
||||
@runtime_checkable # <1>
|
||||
class LoadableRandomPicker(RandomPicker, Protocol): # <2>
|
||||
def load(self, Iterable) -> None: ... # <3>
|
||||
32
13-protocol-abc/typing/randompickload_test.py
Normal file
32
13-protocol-abc/typing/randompickload_test.py
Normal file
@@ -0,0 +1,32 @@
|
||||
import random
|
||||
from typing import Any, Iterable, TYPE_CHECKING
|
||||
|
||||
from randompickload import LoadableRandomPicker
|
||||
|
||||
class SimplePicker():
|
||||
def __init__(self, items: Iterable) -> None:
|
||||
self._items = list(items)
|
||||
random.shuffle(self._items)
|
||||
|
||||
def pick(self) -> Any:
|
||||
return self._items.pop()
|
||||
|
||||
class LoadablePicker(): # <1>
|
||||
def __init__(self, items: Iterable) -> None:
|
||||
self.load(items)
|
||||
|
||||
def pick(self) -> Any: # <2>
|
||||
return self._items.pop()
|
||||
|
||||
def load(self, items: Iterable) -> Any: # <3>
|
||||
self._items = list(items)
|
||||
random.shuffle(self._items)
|
||||
|
||||
def test_isinstance() -> None: # <4>
|
||||
popper = LoadablePicker([1])
|
||||
assert isinstance(popper, LoadableRandomPicker)
|
||||
|
||||
def test_isinstance_not() -> None: # <5>
|
||||
popper = SimplePicker([1])
|
||||
assert not isinstance(popper, LoadableRandomPicker)
|
||||
|
||||
172
13-protocol-abc/typing/vector2d_v4.py
Normal file
172
13-protocol-abc/typing/vector2d_v4.py
Normal file
@@ -0,0 +1,172 @@
|
||||
"""
|
||||
A two-dimensional vector class
|
||||
|
||||
>>> v1 = Vector2d(3, 4)
|
||||
>>> print(v1.x, v1.y)
|
||||
3.0 4.0
|
||||
>>> x, y = v1
|
||||
>>> x, y
|
||||
(3.0, 4.0)
|
||||
>>> v1
|
||||
Vector2d(3.0, 4.0)
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0)
|
||||
>>> octets = bytes(v1)
|
||||
>>> octets
|
||||
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> bool(v1), bool(Vector2d(0, 0))
|
||||
(True, False)
|
||||
|
||||
|
||||
Test of ``.frombytes()`` class method:
|
||||
|
||||
>>> v1_clone = Vector2d.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector2d(3.0, 4.0)
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates:
|
||||
|
||||
>>> format(v1)
|
||||
'(3.0, 4.0)'
|
||||
>>> format(v1, '.2f')
|
||||
'(3.00, 4.00)'
|
||||
>>> format(v1, '.3e')
|
||||
'(3.000e+00, 4.000e+00)'
|
||||
|
||||
|
||||
Tests of the ``angle`` method::
|
||||
|
||||
>>> Vector2d(0, 0).angle()
|
||||
0.0
|
||||
>>> Vector2d(1, 0).angle()
|
||||
0.0
|
||||
>>> epsilon = 10**-8
|
||||
>>> abs(Vector2d(0, 1).angle() - math.pi/2) < epsilon
|
||||
True
|
||||
>>> abs(Vector2d(1, 1).angle() - math.pi/4) < epsilon
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with polar coordinates:
|
||||
|
||||
>>> format(Vector2d(1, 1), 'p') # doctest:+ELLIPSIS
|
||||
'<1.414213..., 0.785398...>'
|
||||
>>> format(Vector2d(1, 1), '.3ep')
|
||||
'<1.414e+00, 7.854e-01>'
|
||||
>>> format(Vector2d(1, 1), '0.5fp')
|
||||
'<1.41421, 0.78540>'
|
||||
|
||||
|
||||
Tests of ``x`` and ``y`` read-only properties:
|
||||
|
||||
>>> v1.x, v1.y
|
||||
(3.0, 4.0)
|
||||
>>> v1.x = 123
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: can't set attribute
|
||||
|
||||
|
||||
Tests of hashing:
|
||||
|
||||
>>> v1 = Vector2d(3, 4)
|
||||
>>> v2 = Vector2d(3.1, 4.2)
|
||||
>>> hash(v1), hash(v2)
|
||||
(7, 384307168202284039)
|
||||
>>> len(set([v1, v2]))
|
||||
2
|
||||
|
||||
Converting to/from a ``complex``:
|
||||
# tag::VECTOR2D_V4_DEMO[]
|
||||
>>> from typing import SupportsComplex
|
||||
>>> v3 = Vector2d(1.5, 2.5)
|
||||
>>> isinstance(v3, SupportsComplex) # <1>
|
||||
True
|
||||
>>> complex(v3) # <2>
|
||||
(1.5+2.5j)
|
||||
>>> Vector2d.fromcomplex(4+5j) # <3>
|
||||
Vector2d(4.0, 5.0)
|
||||
|
||||
# end::VECTOR2D_V4_DEMO[]
|
||||
"""
|
||||
|
||||
from array import array
|
||||
import math
|
||||
|
||||
class Vector2d:
|
||||
typecode = 'd'
|
||||
|
||||
def __init__(self, x, y):
|
||||
self.__x = float(x)
|
||||
self.__y = float(y)
|
||||
|
||||
@property
|
||||
def x(self):
|
||||
return self.__x
|
||||
|
||||
@property
|
||||
def y(self):
|
||||
return self.__y
|
||||
|
||||
def __iter__(self):
|
||||
return (i for i in (self.x, self.y))
|
||||
|
||||
def __repr__(self):
|
||||
class_name = type(self).__name__
|
||||
return '{}({!r}, {!r})'.format(class_name, *self)
|
||||
|
||||
def __str__(self):
|
||||
return str(tuple(self))
|
||||
|
||||
def __bytes__(self):
|
||||
return (bytes([ord(self.typecode)]) +
|
||||
bytes(array(self.typecode, self)))
|
||||
|
||||
def __eq__(self, other):
|
||||
return tuple(self) == tuple(other)
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.x) ^ hash(self.y)
|
||||
|
||||
def __abs__(self):
|
||||
return math.hypot(self.x, self.y)
|
||||
|
||||
def __bool__(self):
|
||||
return bool(abs(self))
|
||||
|
||||
def angle(self):
|
||||
return math.atan2(self.y, self.x)
|
||||
|
||||
def __format__(self, fmt_spec=''):
|
||||
if fmt_spec.endswith('p'):
|
||||
fmt_spec = fmt_spec[:-1]
|
||||
coords = (abs(self), self.angle())
|
||||
outer_fmt = '<{}, {}>'
|
||||
else:
|
||||
coords = self
|
||||
outer_fmt = '({}, {})'
|
||||
components = (format(c, fmt_spec) for c in coords)
|
||||
return outer_fmt.format(*components)
|
||||
|
||||
@classmethod
|
||||
def frombytes(cls, octets):
|
||||
typecode = chr(octets[0])
|
||||
memv = memoryview(octets[1:]).cast(typecode)
|
||||
return cls(*memv)
|
||||
|
||||
# tag::VECTOR2D_V4_COMPLEX[]
|
||||
def __complex__(self):
|
||||
return complex(self.x, self.y)
|
||||
|
||||
@classmethod
|
||||
def fromcomplex(cls, datum):
|
||||
return Vector2d(datum.real, datum.imag) # <1>
|
||||
# end::VECTOR2D_V4_COMPLEX[]
|
||||
56
13-protocol-abc/typing/vector2d_v4_test.py
Normal file
56
13-protocol-abc/typing/vector2d_v4_test.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from typing import SupportsComplex, SupportsAbs, Tuple
|
||||
from typing import TYPE_CHECKING
|
||||
import math
|
||||
import pytest
|
||||
|
||||
from vector2d_v4 import Vector2d
|
||||
|
||||
def test_SupportsComplex_subclass() -> None:
|
||||
assert issubclass(Vector2d, SupportsComplex)
|
||||
|
||||
def test_SupportsComplex_isinstance() -> None:
|
||||
v = Vector2d(3, 4)
|
||||
assert isinstance(v, SupportsComplex)
|
||||
c = complex(v)
|
||||
assert c == 3 + 4j
|
||||
|
||||
def test_SupportsAbs_subclass() -> None:
|
||||
assert issubclass(Vector2d, SupportsAbs)
|
||||
|
||||
def test_SupportsAbs_isinstance() -> None:
|
||||
v = Vector2d(3, 4)
|
||||
assert isinstance(v, SupportsAbs)
|
||||
r = abs(v)
|
||||
assert r == 5.0
|
||||
if TYPE_CHECKING:
|
||||
reveal_type(r) # Revealed type is 'Any'
|
||||
|
||||
def magnitude(v: SupportsAbs) -> float:
|
||||
return abs(v)
|
||||
|
||||
def test_SupportsAbs_Vector2d_argument() -> None:
|
||||
assert magnitude(Vector2d(3, 4)) == 5.0
|
||||
|
||||
def test_SupportsAbs_object_argument() -> None:
|
||||
with pytest.raises(TypeError):
|
||||
magnitude(object())
|
||||
# mypy error:
|
||||
# Argument 1 to "magnitude" has incompatible type "object"; expected "SupportsAbs[Any]"
|
||||
|
||||
def polar(datum: SupportsComplex) -> Tuple[float, float]:
|
||||
c = complex(datum)
|
||||
return abs(c), math.atan2(c.imag, c.real)
|
||||
|
||||
def test_SupportsComplex_Vector2d_argument() -> None:
|
||||
assert polar(Vector2d(2, 0)) == (2, 0)
|
||||
expected = (2, math.pi / 2)
|
||||
result = polar(Vector2d(0, 2))
|
||||
assert math.isclose(result[0], expected[0])
|
||||
assert math.isclose(result[1], expected[1])
|
||||
|
||||
def test_SupportsComplex_complex_argument() -> None:
|
||||
assert polar(complex(2, 0)) == (2, 0)
|
||||
expected = (2, math.pi / 2)
|
||||
result = polar(complex(0, 2))
|
||||
assert math.isclose(result[0], expected[0])
|
||||
assert math.isclose(result[1], expected[1])
|
||||
174
13-protocol-abc/typing/vector2d_v5.py
Normal file
174
13-protocol-abc/typing/vector2d_v5.py
Normal file
@@ -0,0 +1,174 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
A two-dimensional vector class
|
||||
|
||||
>>> v1 = Vector2d(3, 4)
|
||||
>>> print(v1.x, v1.y)
|
||||
3.0 4.0
|
||||
>>> x, y = v1
|
||||
>>> x, y
|
||||
(3.0, 4.0)
|
||||
>>> v1
|
||||
Vector2d(3.0, 4.0)
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0)
|
||||
>>> octets = bytes(v1)
|
||||
>>> octets
|
||||
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> bool(v1), bool(Vector2d(0, 0))
|
||||
(True, False)
|
||||
|
||||
|
||||
Test of ``.frombytes()`` class method:
|
||||
|
||||
>>> v1_clone = Vector2d.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector2d(3.0, 4.0)
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates:
|
||||
|
||||
>>> format(v1)
|
||||
'(3.0, 4.0)'
|
||||
>>> format(v1, '.2f')
|
||||
'(3.00, 4.00)'
|
||||
>>> format(v1, '.3e')
|
||||
'(3.000e+00, 4.000e+00)'
|
||||
|
||||
|
||||
Tests of the ``angle`` method::
|
||||
|
||||
>>> Vector2d(0, 0).angle()
|
||||
0.0
|
||||
>>> Vector2d(1, 0).angle()
|
||||
0.0
|
||||
>>> epsilon = 10**-8
|
||||
>>> abs(Vector2d(0, 1).angle() - math.pi/2) < epsilon
|
||||
True
|
||||
>>> abs(Vector2d(1, 1).angle() - math.pi/4) < epsilon
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with polar coordinates:
|
||||
|
||||
>>> format(Vector2d(1, 1), 'p') # doctest:+ELLIPSIS
|
||||
'<1.414213..., 0.785398...>'
|
||||
>>> format(Vector2d(1, 1), '.3ep')
|
||||
'<1.414e+00, 7.854e-01>'
|
||||
>>> format(Vector2d(1, 1), '0.5fp')
|
||||
'<1.41421, 0.78540>'
|
||||
|
||||
|
||||
Tests of ``x`` and ``y`` read-only properties:
|
||||
|
||||
>>> v1.x, v1.y
|
||||
(3.0, 4.0)
|
||||
>>> v1.x = 123
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: can't set attribute
|
||||
|
||||
|
||||
Tests of hashing:
|
||||
|
||||
>>> v1 = Vector2d(3, 4)
|
||||
>>> v2 = Vector2d(3.1, 4.2)
|
||||
>>> hash(v1), hash(v2)
|
||||
(7, 384307168202284039)
|
||||
>>> len(set([v1, v2]))
|
||||
2
|
||||
|
||||
Converting to/from a ``complex``:
|
||||
|
||||
>>> from typing import SupportsComplex
|
||||
>>> v3 = Vector2d(1.5, 2.5)
|
||||
>>> isinstance(v3, SupportsComplex) # <1>
|
||||
True
|
||||
>>> complex(v3) # <2>
|
||||
(1.5+2.5j)
|
||||
>>> Vector2d.fromcomplex(4+5j) # <3>
|
||||
Vector2d(4.0, 5.0)
|
||||
"""
|
||||
|
||||
from array import array
|
||||
import math
|
||||
from typing import SupportsComplex, Iterator
|
||||
|
||||
class Vector2d:
|
||||
typecode = 'd'
|
||||
|
||||
def __init__(self, x, y) -> None:
|
||||
self.__x = float(x)
|
||||
self.__y = float(y)
|
||||
|
||||
@property
|
||||
def x(self) -> float:
|
||||
return self.__x
|
||||
|
||||
@property
|
||||
def y(self) -> float:
|
||||
return self.__y
|
||||
|
||||
def __iter__(self) -> Iterator[float]:
|
||||
return (i for i in (self.x, self.y))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
class_name = type(self).__name__
|
||||
return '{}({!r}, {!r})'.format(class_name, *self)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(tuple(self))
|
||||
|
||||
def __bytes__(self) -> bytes:
|
||||
return (bytes([ord(self.typecode)]) +
|
||||
bytes(array(self.typecode, self)))
|
||||
|
||||
def __eq__(self, other) -> bool:
|
||||
return tuple(self) == tuple(other)
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash(self.x) ^ hash(self.y)
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
return bool(abs(self))
|
||||
|
||||
def angle(self) -> float:
|
||||
return math.atan2(self.y, self.x)
|
||||
|
||||
def __format__(self, fmt_spec='') -> str:
|
||||
if fmt_spec.endswith('p'):
|
||||
fmt_spec = fmt_spec[:-1]
|
||||
coords = (abs(self), self.angle())
|
||||
outer_fmt = '<{}, {}>'
|
||||
else:
|
||||
coords = self
|
||||
outer_fmt = '({}, {})'
|
||||
components = (format(c, fmt_spec) for c in coords)
|
||||
return outer_fmt.format(*components)
|
||||
|
||||
@classmethod
|
||||
def frombytes(cls, octets) -> Vector2d:
|
||||
typecode = chr(octets[0])
|
||||
memv = memoryview(octets[1:]).cast(typecode)
|
||||
return cls(*memv)
|
||||
|
||||
# tag::VECTOR2D_V5_COMPLEX[]
|
||||
def __abs__(self) -> float: # <1>
|
||||
return math.hypot(self.x, self.y)
|
||||
|
||||
def __complex__(self) -> complex: # <2>
|
||||
return complex(self.x, self.y)
|
||||
|
||||
@classmethod
|
||||
def fromcomplex(cls, datum: SupportsComplex) -> Vector2d: # <3>
|
||||
c = complex(datum) # <4>
|
||||
return Vector2d(c.real, c.imag)
|
||||
# end::VECTOR2D_V5_COMPLEX[]
|
||||
35
13-protocol-abc/typing/vector2d_v5_test.py
Normal file
35
13-protocol-abc/typing/vector2d_v5_test.py
Normal file
@@ -0,0 +1,35 @@
|
||||
from vector2d_v5 import Vector2d
|
||||
from typing import SupportsComplex, SupportsAbs, TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_SupportsComplex_subclass() -> None:
|
||||
assert issubclass(Vector2d, SupportsComplex)
|
||||
|
||||
def test_SupportsComplex_isinstance() -> None:
|
||||
v = Vector2d(3, 4)
|
||||
assert isinstance(v, SupportsComplex)
|
||||
c = complex(v)
|
||||
assert c == 3 + 4j
|
||||
|
||||
def test_SupportsAbs_subclass() -> None:
|
||||
assert issubclass(Vector2d, SupportsAbs)
|
||||
|
||||
def test_SupportsAbs_isinstance() -> None:
|
||||
v = Vector2d(3, 4)
|
||||
assert isinstance(v, SupportsAbs)
|
||||
r = abs(v)
|
||||
assert r == 5.0
|
||||
if TYPE_CHECKING:
|
||||
reveal_type(r) # Revealed type is 'builtins.float*'
|
||||
|
||||
def magnitude(v: SupportsAbs) -> float:
|
||||
return abs(v)
|
||||
|
||||
def test_SupportsAbs_Vector2d_argument() -> None:
|
||||
assert 5.0 == magnitude(Vector2d(3, 4))
|
||||
|
||||
def test_SupportsAbs_object_argument() -> None:
|
||||
with pytest.raises(TypeError):
|
||||
assert 5.0 == magnitude(object())
|
||||
Reference in New Issue
Block a user