Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Eliminate dependency on phantom-types #45

Merged
merged 2 commits into from
Jun 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ repos:
additional_dependencies:
- pytest==7.1.3
- types-setuptools==65.3.0
- phantom-types==0.17.1
- abcattrs==0.3.2
- typing-extensions==4.6.3
- hypothesis==6.54.4
Expand Down
1 change: 0 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ package_dir =
packages = find:
python_requires = >=3.10
install_requires =
phantom-types>=2.1.0
typing-extensions>=4.6.3
abcattrs>=0.3.2

Expand Down
10 changes: 9 additions & 1 deletion src/immoney/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
from ._base import Currency
from ._base import Money
from ._base import Overdraft
from ._base import ParsableMoneyValue
from ._base import Round
from ._base import SubunitFraction

__all__ = ("Money", "Currency", "SubunitFraction", "Round", "Overdraft")
__all__ = (
"Money",
"Currency",
"SubunitFraction",
"Round",
"Overdraft",
"ParsableMoneyValue",
)
__version__ = "0.2.0"
36 changes: 23 additions & 13 deletions src/immoney/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
from typing import ClassVar
from typing import Final
from typing import Generic
from typing import NewType
from typing import TypeAlias
from typing import TypeVar
from typing import cast
from typing import final
from typing import overload

Expand All @@ -32,14 +33,15 @@
from .errors import DivisionByZero
from .errors import InvalidSubunit
from .errors import MoneyParseError
from .types import ParsableMoneyValue
from .types import PositiveDecimal

if TYPE_CHECKING:
from pydantic_core.core_schema import CoreSchema

from .registry import CurrencyRegistry

ParsableMoneyValue: TypeAlias = int | str | Decimal
PositiveDecimal = NewType("PositiveDecimal", Decimal)

valid_subunit: Final = frozenset({10**i for i in range(20)})


Expand Down Expand Up @@ -80,23 +82,31 @@ def zero(self) -> Money[Self]:
return Money(0, self)

def normalize_value(self, value: Decimal | int | str) -> PositiveDecimal:
try:
positive = PositiveDecimal.parse(value)
except TypeError as e:
raise MoneyParseError(
"Failed to interpret value as non-negative decimal"
) from e
if not isinstance(value, Decimal):
try:
value = Decimal(value)
except decimal.InvalidOperation:
raise MoneyParseError("Failed parsing Decimal")

if value.is_nan():
raise MoneyParseError("Cannot parse from NaN")

if not value.is_finite():
raise MoneyParseError("Cannot parse from non-finite")

if value < 0:
raise MoneyParseError("Cannot parse from negative value")

quantized = cast(PositiveDecimal, positive.quantize(self.decimal_exponent))
quantized = value.quantize(self.decimal_exponent)

if positive != quantized:
if value != quantized:
raise MoneyParseError(
f"Cannot interpret value as Money of currency {self.code} without loss "
f"of precision. Explicitly round the value or consider using "
f"SubunitFraction."
)

return quantized
return PositiveDecimal(quantized)

def from_subunit(self, value: int) -> Money[Self]:
return Money.from_subunit(value, self)
Expand Down Expand Up @@ -153,7 +163,7 @@ def _normalize(
value: ParsableMoneyValue,
currency: C_inv,
/,
) -> tuple[Decimal, C_inv]:
) -> tuple[PositiveDecimal, C_inv]:
if not isinstance(currency, Currency):
raise TypeError(
f"Argument 'currency' of {cls.__qualname__!r} must be a Currency, "
Expand Down
34 changes: 0 additions & 34 deletions src/immoney/types.py

This file was deleted.

25 changes: 12 additions & 13 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ class Subclass(Currency):
"0." + len(str(subunit_value)) * "0"
)

def test_zero_returns_cached_instance_of_money_zero(self):
def test_zero_returns_cached_instance_of_money_zero(self) -> None:
assert SEK.zero is SEK.zero
assert SEK.zero.value == 0
assert SEK.zero.currency is SEK
Expand All @@ -138,30 +138,29 @@ def test_normalize_value_raises_for_precision_loss(
self,
currency: Currency,
value: Decimal,
):
) -> None:
with pytest.raises((MoneyParseError, InvalidOperation)):
currency.normalize_value(value)
currency.normalize_value(value + very_small_decimal)

@given(
currency=currencies(),
value=integers(max_value=-1) | decimals(max_value=Decimal("-0.000001")),
)
def test_normalize_value_raises_for_negative_value(
self, currency: Currency, value: object
):
def test_normalize_value_raises_for_negative_value(self, value: object) -> None:
with pytest.raises(MoneyParseError):
SEK.normalize_value(value) # type: ignore[arg-type]

def test_normalize_value_raises_for_invalid_str(self) -> None:
with pytest.raises(MoneyParseError):
currency.normalize_value(value) # type: ignore[arg-type]
SEK.normalize_value("foo")

@given(currencies())
def test_normalize_value_raises_for_invalid_str(self, currency: Currency):
def test_normalize_value_raises_for_nan(self) -> None:
with pytest.raises(MoneyParseError):
currency.normalize_value("foo")
SEK.normalize_value(Decimal("nan"))

@given(currencies())
def test_normalize_value_raises_for_nan(self, currency: Currency):
def test_normalize_value_raises_for_non_finite(self) -> None:
with pytest.raises(MoneyParseError):
currency.normalize_value(Decimal("nan"))
SEK.normalize_value(float("inf")) # type: ignore[arg-type]


valid_values = decimals(
Expand Down