Skip to content

Commit cc610b2

Browse files
committed
Class for defining a subgroup in an already existing type
1 parent dd35699 commit cc610b2

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

pyannotating.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,41 @@ def __class_getitem__(cls, annotation_resource: tuple[Any, Any] | Any) -> Any:
200200
return annotation_resource[1]
201201

202202

203+
_BasicT = TypeVar("_BasicT")
204+
205+
206+
class Subgroup(Generic[_BasicT]):
207+
"""
208+
Class for defining a subgroup in an already existing type.
209+
210+
Delegates the definition of a subgroup from a particular type to
211+
`determinant` attribute.
212+
"""
213+
214+
def __init__(self, type_: Type[_BasicT], determinant: Callable[[_BasicT], bool]):
215+
self._type = type_
216+
self._determinant = determinant
217+
218+
@property
219+
def type_(self) -> Type[_BasicT]:
220+
return self._type
221+
222+
@property
223+
def determinant(self) -> Callable[[_BasicT], bool]:
224+
return self._determinant
225+
226+
def __instancecheck__(self, instance: Any) -> bool:
227+
return self._has(instance)
228+
229+
def __contains__(self, object_: Any) -> bool:
230+
return self._has(object_)
231+
232+
def __repr__(self) -> str:
233+
return f"<{self.__class__.__name__} of {self._type.__name__}>"
234+
235+
def _has(self, object_: Any) -> bool:
236+
return isinstance(object_, self.type_) and self._determinant(object_)
237+
203238

204239
# Pre-created instance without permanent formal creation of a new one.
205240
input_annotation: Final[_InputAnnotationAnnotation] = _InputAnnotationAnnotation()

0 commit comments

Comments
 (0)