Skip to content

Commit 2069ff6

Browse files
committed
Update base model behavior
* hi3-avatar-sorter/models/base.py: - Remove the `__init_subclass__` method. - Make the `validate_id` method strip the ID before justifying it. - Make the numeric validation occur before the length check in the `validate_id` method. - Adapt the `__getattribute__` method to the `super()` bug in older versions of CPython: python/cpython#90562. - Improve readability of the `AttributeError` message. - Improve readability of the `__str__` method. * hi3-avatar-sorter/models/battlesuit.py: - Remove the unused `field` import.
1 parent 2ee9440 commit 2069ff6

2 files changed

Lines changed: 9 additions & 14 deletions

File tree

‎hi3-avatar-sorter/models/base.py‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from typing import Any, ClassVar
33

44
from ..errors import NonNumericIDError, TooLongIDError
5+
from ..utils import capitalize, snake_case
56

67

78
@dataclass(frozen=True, slots=True)
@@ -11,30 +12,24 @@ class BaseModel:
1112
no: int = field(init=False)
1213
id_length: ClassVar[int] = 2
1314

14-
def __init_subclass__(cls) -> None:
15-
super().__init_subclass__()
16-
17-
if getattr(cls, "__hash__", None) is None:
18-
cls.__hash__ = BaseModel.__hash__
19-
2015
def __post_init__(self) -> None:
2116
object.__setattr__(self, "id", self.validate_id(self.id))
2217

2318
@classmethod
2419
def validate_id(cls, id: str) -> str:
25-
id = id.rjust(cls.id_length, "0")
26-
27-
if len(id) > cls.id_length:
28-
raise TooLongIDError(id, cls.id_length, cls.__name__)
20+
id = id.strip().rjust(cls.id_length, "0")
2921

3022
if not id.isnumeric():
3123
raise NonNumericIDError(id, cls.__name__)
3224

25+
if len(id) > cls.id_length:
26+
raise TooLongIDError(id, cls.id_length, cls.__name__)
27+
3328
return id
3429

3530
def __getattribute__(self, name: str) -> Any:
3631
try:
37-
return super().__getattribute__(name)
32+
return object.__getattribute__(self, name)
3833

3934
except AttributeError:
4035
class_name = type(self).__name__
@@ -44,7 +39,7 @@ def __getattribute__(self, name: str) -> Any:
4439
raise AttributeError(
4540
base_message +
4641
f" Perhaps it was created without using the "
47-
f"'get_or_add_{class_name}' method?"
42+
f"'get_or_add_{snake_case(class_name)}' method?"
4843
)
4944

5045
raise
@@ -53,7 +48,7 @@ def __int__(self) -> int:
5348
return self.no
5449

5550
def __str__(self) -> str:
56-
return f"№{int(self)}"
51+
return f"{capitalize(type(self).__name__)} №{int(self)}"
5752

5853
def __hash__(self) -> int:
5954
return hash((self.id, self.no))

‎hi3-avatar-sorter/models/battlesuit.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from dataclasses import dataclass, field
1+
from dataclasses import dataclass
22

33
from .base import BaseModel
44
from .skin_rarity import SkinRarity

0 commit comments

Comments
 (0)