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

Code quality improvements #283

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
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: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ coverage.xml
*.cover
.hypothesis/
.pytest_cache/
.ruff_cache/

# Translations
*.mo
Expand Down
22 changes: 17 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,17 +96,29 @@ select = [
]
ignore = [
"UP007", # union type annotations
"UP006", # type instead of Type
"PLR0913", # too many arguments
"UP037", # type annotation with quotes

]
src = [
"src",
"tests",
"stockholm",
"tests",
]

[tool.ruff.per-file-ignores]
"tests/**/*.py" = [
"S101", # assert
"I003", # isort
"PLR2004", # magic-value-comparison
"S101", # assert
"PLR2004", # magic-value-comparison
]
"stockholm/protobuf/money_pb2.py*" = [
"UP009", # utf-8 encoding
"SLF001", # private member accessed
"E501", # line too long
"I001", # isort
"UP036", # version block outdated
"N802", # camelcase function
"N816", # mixedcase variable
]

[tool.mypy]
Expand Down
11 changes: 6 additions & 5 deletions stockholm/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from .__version__ import __version__, __version_info__ # noqa
from .currency import BaseCurrency, Currency, CurrencyValue, DefaultCurrency, DefaultCurrencyValue, get_currency # noqa
from .exceptions import ConversionError, CurrencyMismatchError, InvalidOperandError, MoneyException # noqa
from .money import Money, MoneyType # noqa
from .__version__ import __version__, __version_info__
from .currency import BaseCurrency, Currency, CurrencyValue, DefaultCurrency, DefaultCurrencyValue, get_currency
from .exceptions import ConversionError, CurrencyMismatchError, InvalidOperandError, MoneyException, MoneyExceptionError
from .money import Money, MoneyType
from .protobuf import MoneyProtobufMessage
from .rate import ExchangeRate, Number, Rate # noqa
from .rate import ExchangeRate, Number, Rate

__author__ = "Carl Oscar Aaro"
__email__ = "[email protected]"
Expand All @@ -23,6 +23,7 @@
"CurrencyMismatchError",
"InvalidOperandError",
"MoneyException",
"MoneyExceptionError",
"Money",
"MoneyProtobufMessage",
"MoneyType",
Expand Down
15 changes: 10 additions & 5 deletions stockholm/__version__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
__version_info__ = (0, 5, 7)
__version__ = "".join([".{}".format(str(n)) if type(n) is int else str(n) for n in __version_info__]).replace(
".", "", 1 if type(__version_info__[0]) is int else 0
)
from typing import Tuple, Union

__version_info__: Tuple[Union[int, str], ...] = (0, 5, 7)
__version__: str = "".join(
[
f".{n}" if isinstance(n, int) or str(n).isdigit() or str(n)[0:4] == "post" or str(n)[0:3] == "dev" else f"{n}"
for n in __version_info__
]
).strip(".")

if __name__ == "__main__": # pragma: no cover
print(__version__)
print(__version__) # noqa: T201
74 changes: 37 additions & 37 deletions stockholm/currency.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def __new__(cls: Type[MetaCurrency], name: str, bases: Tuple[type, ...], attribu
return cast(Type["BaseCurrency"], super().__new__(cls, name, bases, attributedict))

def money(
self,
cls,
amount: Optional[Union["Money", Decimal, int, float, str, object]] = None,
from_sub_units: Optional[bool] = None,
units: Optional[int] = None,
Expand All @@ -67,7 +67,7 @@ def money(

return Money(
amount,
currency=self,
currency=cls,
from_sub_units=from_sub_units,
units=units,
nanos=nanos,
Expand All @@ -76,65 +76,65 @@ def money(
**kwargs,
)

def __setattr__(self, *args: Any) -> None:
def __setattr__(cls, *args: Any) -> None:
raise AttributeError("Attributes of currencies cannot be changed")

def __delattr__(self, *args: Any) -> None:
def __delattr__(cls, *args: Any) -> None:
raise AttributeError("Attributes of currencies cannot be deleted")

def __repr__(self) -> str:
if self._meta:
def __repr__(cls) -> str:
if cls._meta:
return "<class 'stockholm.currency.Currency'>"
return f'<stockholm.Currency: "{self}">'
return f'<stockholm.Currency: "{cls}">'

def __str__(self) -> str:
if self._meta:
def __str__(cls) -> str:
if cls._meta:
return "<class 'stockholm.currency.Currency'>"
return self.ticker or ""
return cls.ticker or ""

def __format__(self, format_spec: str) -> str:
output = str(self)
def __format__(cls, format_spec: str) -> str:
output = str(cls)
if format_spec.endswith("c"):
format_spec = f"{format_spec[:-1]}s"
return f"{output:{format_spec}}"

def __eq__(self, other: Any) -> bool:
if self.ticker:
def __eq__(cls, other: Any) -> bool:
if cls.ticker:
if not other:
return False
elif isinstance(other, BaseCurrency):
return bool(self.ticker == other.ticker)
elif isinstance(other, str):
return bool(self.ticker == other)
if isinstance(other, BaseCurrency):
return bool(cls.ticker == other.ticker)
if isinstance(other, str):
return bool(cls.ticker == other)
else:
if isinstance(other, BaseCurrency):
return not other.ticker
elif isinstance(other, str):
if isinstance(other, str):
return bool(other == "")
return False

def __ne__(self, other: Any) -> bool:
return not self == other
def __ne__(cls, other: Any) -> bool:
return not cls == other

@property # type: ignore
def __class__(self) -> Any:
@property # type: ignore[misc]
def __class__(cls) -> Any:
return BaseCurrency

def __hash__(self) -> int:
def __hash__(cls) -> int:
return hash(
(
"stockholm.MetaCurrency",
self.ticker,
self.decimal_digits,
self.interchangeable_with,
self.preferred_ticker,
cls.ticker,
cls.decimal_digits,
cls.interchangeable_with,
cls.preferred_ticker,
)
)

def __bool__(self) -> bool:
return bool(self.ticker)
def __bool__(cls) -> bool:
return bool(cls.ticker)

def __instancecheck__(self, instance: Any) -> bool:
def __instancecheck__(cls, instance: Any) -> bool:
return_value = super().__instancecheck__(instance)
if not return_value and type(instance) is BaseCurrencyType:
return True
Expand Down Expand Up @@ -178,7 +178,7 @@ def json_schema(schema: Any) -> Any:
if schema.get("type") == "is-instance":
return None
return {k: json_schema(v) for k, v in schema.items() if json_schema(v) is not None}
elif isinstance(schema, list):
if isinstance(schema, list):
return [json_schema(v) for v in schema if json_schema(v) is not None]
return schema

Expand Down Expand Up @@ -288,14 +288,14 @@ def __eq__(self, other: Any) -> bool:
if self.ticker:
if not other:
return False
elif isinstance(other, BaseCurrency):
if isinstance(other, BaseCurrency):
return bool(self.ticker == other.ticker)
elif isinstance(other, str):
if isinstance(other, str):
return bool(self.ticker == other)
else:
if isinstance(other, BaseCurrency):
return not other.ticker
elif isinstance(other, str):
if isinstance(other, str):
return bool(other == "")
return False

Expand Down Expand Up @@ -1627,7 +1627,7 @@ def get_currency(ticker: str) -> BaseCurrency:
return cast(BaseCurrency, getattr(sys.modules[__name__], ticker, BaseCurrency(ticker)))


# Note to future self this is generally bad practice (but helps with type hint annotations).
# Note to future self - this is generally bad practice (but helps with type hint annotations).
class Currency(BaseCurrency):
ADF = ADF
ADP = ADP
Expand Down Expand Up @@ -1952,4 +1952,4 @@ def __set__(self, instance: Any, value: CurrencyValue) -> None:
...


from stockholm.money import Money # noqa isort:skip
from stockholm.money import Money # noqa: E402
7 changes: 6 additions & 1 deletion stockholm/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
class MoneyException(Exception):
class MoneyExceptionError(Exception):
pass


# deprecated: use `MoneyExceptionError` instead of `MoneyException`
class MoneyException(MoneyExceptionError): # noqa: N818
pass


Expand Down
Loading