Skip to content

Commit

Permalink
feat: Vector init and type hinting
Browse files Browse the repository at this point in the history
  • Loading branch information
unexcellent committed Nov 13, 2024
1 parent 991c2b5 commit 5dd38de
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ repos:
name: Run Type Checker
types_or: [python, pyi, toml, yaml]
pass_filenames: false
args: [quantio]
args: [quantio, test]

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.0
Expand Down
2 changes: 2 additions & 0 deletions quantio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from .exceptions import CanNotAddTypesError, CanNotSubtractTypesError
from .quantities import Acceleration, Angle, Area, Length, Mass, Time, Velocity
from .vector import Vector

__all__ = [
"Acceleration",
Expand All @@ -11,6 +12,7 @@
"Mass",
"Time",
"Velocity",
"Vector",
"CanNotAddTypesError",
"CanNotSubtractTypesError",
]
21 changes: 21 additions & 0 deletions quantio/vector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from __future__ import annotations

from typing import Generic, TypeVar

import numpy as np

T = TypeVar("T")


class Vector(Generic[T]):
"""A vector of either quanity or numeric elements."""

_elements: np.array

def __init__(self, elements: list | tuple | np.ndarray) -> None:
self._elements = np.array(elements)

@classmethod
def __class_getitem__(cls, *_: object) -> type:
"""Return this class for type hinting."""
return cls
4 changes: 2 additions & 2 deletions test/test_quantities_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def test_add__false_class():
length = Length(meters=1)

with pytest.raises(CanNotAddTypesError):
length += 1
length += 1 # type: ignore


def test_sub__success():
Expand All @@ -35,7 +35,7 @@ def test_sub__false_class():
length = Length(meters=1)

with pytest.raises(CanNotSubtractTypesError):
length -= 1
length -= 1 # type: ignore


if __name__ == "__main__":
Expand Down
19 changes: 19 additions & 0 deletions test/test_vector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import pytest

import numpy as np

from quantio import Vector, Length


def test_init():
actual: Vector[Length] = Vector([Length.zero(), Length.zero()])
assert np.all(actual._elements == np.array([Length.zero(), Length.zero()]))


def test_init_with_type_hint():
actual = Vector[Length]([Length.zero(), Length.zero()])
assert np.all(actual._elements == np.array([Length.zero(), Length.zero()]))


if __name__ == "__main__":
pytest.main([__file__, "-v"])

0 comments on commit 5dd38de

Please sign in to comment.