Skip to content
This repository was archived by the owner on Mar 31, 2020. It is now read-only.

Commit abed876

Browse files
committed
Coord docstrings
1 parent d09b131 commit abed876

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

src/animation.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from __future__ import annotations
2+
3+
import operator
4+
from typing import NamedTuple, Callable, TypeVar
5+
from functools import partialmethod
6+
7+
8+
class Coord(NamedTuple):
9+
"""
10+
Helper class for managing coordinate values.
11+
12+
Coord overloads many of the numeric operators by applying
13+
it to the x and y value.
14+
15+
param
16+
x: float -- X position.
17+
y: float -- Y position
18+
19+
# Usage
20+
The operators will behave like you applied the to each value.
21+
```py
22+
c1 = c2 = Coord(1, 1)
23+
c1 + c2
24+
>>> Coord(2, 2)
25+
```
26+
For convenience, integers are accepted as well
27+
```py
28+
c1 = Coord(1, 1)
29+
c1 + 1 # 1 is cast to Coord(1, 1)
30+
>>> Coord(2, 2)
31+
"""
32+
33+
x: int
34+
y: int
35+
36+
Operand = TypeVar('Operand', 'Coord', int)
37+
38+
def __apply(self, op: Callable, other: Coord.Operand) -> Coord:
39+
if isinstance(other, int):
40+
other = Coord(other, other)
41+
42+
x = op(self.x, other.x)
43+
y = op(self.y, other.y)
44+
return Coord(x, y)
45+
46+
@property
47+
def midpoint(self) -> Coord:
48+
return self // Coord(2, 2)
49+
50+
__add__ = partialmethod(__apply, operator.add)
51+
__sub__ = partialmethod(__apply, operator.sub)
52+
__mul__ = partialmethod(__apply, operator.mul)
53+
__mod__ = partialmethod(__apply, operator.mod)
54+
__pow__ = partialmethod(__apply, operator.pow)
55+
__truediv__ = partialmethod(__apply, operator.truediv)
56+
__floordiv__ = partialmethod(__apply, operator.floordiv)

0 commit comments

Comments
 (0)