Skip to content

Commit 05e4019

Browse files
authored
Make Category immutable and add tests (#1206)
1 parent a7f4e85 commit 05e4019

2 files changed

Lines changed: 34 additions & 12 deletions

File tree

sahi/annotation.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -145,25 +145,20 @@ def __repr__(self):
145145
return f"BoundingBox: <{(self.minx, self.miny, self.maxx, self.maxy)}, w: {self.maxx - self.minx}, h: {self.maxy - self.miny}>"
146146

147147

148+
@dataclass(frozen=True)
148149
class Category:
149150
"""
150151
Category of the annotation.
151152
"""
152153

153-
def __init__(self, id=None, name=None):
154-
"""
155-
Args:
156-
id: int
157-
ID of the object category
158-
name: str
159-
Name of the object category
160-
"""
161-
if not isinstance(id, int):
154+
id: int
155+
name: str
156+
157+
def __post_init__(self):
158+
if not isinstance(self.id, int):
162159
raise TypeError("id should be integer")
163-
if not isinstance(name, str):
160+
if not isinstance(self.name, str):
164161
raise TypeError("name should be string")
165-
self.id = id
166-
self.name = name
167162

168163
def __repr__(self):
169164
return f"Category: <id: {self.id}, name: {self.name}>"

tests/test_annotation.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,33 @@ def test_category(self):
6363
assert category.id == category_id
6464
assert category.name == category_name
6565

66+
# id must be int
67+
with pytest.raises(TypeError):
68+
Category(id="not-an-int", name="car")
69+
70+
# name must be str
71+
with pytest.raises(TypeError):
72+
Category(id=1, name=123)
73+
74+
def test_category_immutability(self):
75+
import dataclasses
76+
77+
from sahi.annotation import Category
78+
79+
category = Category(id=5, name="person")
80+
81+
# Attempt to mutate the id directly
82+
with pytest.raises(dataclasses.FrozenInstanceError):
83+
category.id = 10
84+
85+
# Attempt to mutate the name directly
86+
with pytest.raises(dataclasses.FrozenInstanceError):
87+
category.name = "cat"
88+
89+
# Confirm the values remain unchanged
90+
assert category.id == 5
91+
assert category.name == "person"
92+
6693
def test_mask(self):
6794
from sahi.annotation import Mask
6895

0 commit comments

Comments
 (0)