-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Accept function values for IntoMoney
Fixes #7.
- Loading branch information
Showing
2 changed files
with
37 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,29 @@ | ||
from collections.abc import Callable | ||
from decimal import Decimal | ||
from typing import Any, Union | ||
from typing import Any | ||
|
||
from stockholm import Money, MoneyType | ||
from stockholm import Money | ||
from stockholm.money import MoneyModel | ||
|
||
IntoMoneyType = Union[MoneyType, MoneyModel[Any], Decimal, int, float, str, object] | ||
type IntoMoneyType = MoneyModel[Money] | Decimal | int | float | str | ||
|
||
type IntoMoneyCallback = Callable[[Any], IntoMoneyType] | ||
|
||
|
||
class IntoMoney: | ||
def __set_name__(self, owner: Any, name: str): | ||
self._name = "_" + name | ||
|
||
def __get__(self, instance, owner=None) -> Money: | ||
return getattr(instance, self._name) | ||
def __get__(self, instance: Any, owner=None) -> Money: | ||
attr: Money | IntoMoneyCallback = getattr(instance, self._name) | ||
|
||
if isinstance(attr, Money): | ||
return attr | ||
|
||
return Money(attr(instance)) | ||
|
||
def __set__(self, instance, value: IntoMoneyType | IntoMoneyCallback): | ||
if not callable(value): | ||
value = Money(value) | ||
|
||
def __set__(self, instance, value: IntoMoneyType): | ||
setattr(instance, self._name, Money(value)) | ||
setattr(instance, self._name, value) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters