Coverage for qubalab/objects/classification.py: 91%
32 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-31 11:24 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-31 11:24 +0000
1from __future__ import annotations
2import random
5class Classification(object):
6 """
7 Simple class to store the name and color of a classification.
8 """
9 _cached_classifications = {}
11 def __init__(self, name: str, color: tuple[int, int, int] = None):
12 """
13 :param name: the name of the classification
14 :param color: the RGB color (each component between 0 and 255) of the classification. Can be None to use a random color
15 """
16 self._name = name
17 self._color = [random.randint(0, 255) for _ in range(3)] if color is None else color
19 @property
20 def name(self) -> str:
21 """
22 The name of the classification.
23 """
24 return self._name
26 @property
27 def color(self) -> tuple[int, int, int]:
28 """
29 The color of the classification.
30 """
31 return self._color
33 @staticmethod
34 def get_cached_classification(name: str, color: tuple[int, int, int] = None) -> Classification:
35 """
36 Return a classification by looking at an internal cache.
38 If no classification with the provided name is present in the cache, a
39 new classification is created and the cache is updated.
41 This is useful if you want to avoid creating multiple classifications with the
42 same name and use only one instead.
44 :param name: the name of the classification (can be None)
45 :param color: the RGB color (each component between 0 and 255) of the classification.
46 Can be None to use a random color. This is only used if the cache doesn't
47 already contain a classification with the provided name
48 :return: a classification with the provided name, but not always with the provided color
49 if a classification with the same name already existed in the cache. If the provided
50 name is None, None is also returned
51 """
52 if name is None:
53 return None
55 classification = Classification._cached_classifications.get(name)
56 if classification is None:
57 classification = Classification(name, color)
58 Classification._cached_classifications[classification.name] = classification
59 return classification
61 def __str__(self):
62 return f"Classification {self._name} of color {self._color}"
64 def __repr__(self):
65 return f"Classification('{self._name}', {self._color})"
67 def __eq__(self, other):
68 if isinstance(other, Classification):
69 return self._name == other._name and self._color == other._color
70 return False
72 def __hash__(self):
73 return hash(self._name)