0
# Base Types
1
2
Core foundation classes that provide the building blocks for all other comparison types in dirty-equals. These classes include the abstract base class, universal matchers, and choice validators that form the foundation of the library's architecture.
3
4
## Capabilities
5
6
### DirtyEquals
7
8
The abstract base class that all dirty-equals comparison types inherit from. Provides the core equality method overriding and operator support that enables the library's declarative comparison functionality.
9
10
```python { .api }
11
class DirtyEquals:
12
"""
13
Abstract base class for all dirty-equals comparison types.
14
15
Provides the foundation for custom equality checking through the equals() method
16
and supports boolean logic operators for combining comparisons.
17
"""
18
19
def __init__(self, *repr_args: Any, **repr_kwargs: Any):
20
"""
21
Initialize a DirtyEquals instance.
22
23
Args:
24
*repr_args: Arguments used for string representation
25
**repr_kwargs: Keyword arguments used for string representation
26
"""
27
28
def equals(self, other: Any) -> bool:
29
"""
30
Abstract method that subclasses must implement to define comparison logic.
31
32
Args:
33
other: The value to compare against
34
35
Returns:
36
bool: True if the comparison succeeds, False otherwise
37
"""
38
39
@property
40
def value(self) -> Any:
41
"""
42
Get the last value that was successfully compared.
43
44
Returns:
45
The last value that passed the equals() check
46
"""
47
48
def __eq__(self, other: Any) -> bool:
49
"""
50
Implements equality checking by calling equals() method.
51
52
Args:
53
other: Value to compare against
54
55
Returns:
56
bool: Result of equals() method
57
"""
58
59
def __ne__(self, other: Any) -> bool:
60
"""
61
Implements inequality checking (opposite of __eq__).
62
63
Args:
64
other: Value to compare against
65
66
Returns:
67
bool: Opposite of equals() result
68
"""
69
70
def __or__(self, other: 'DirtyEquals') -> 'DirtyOr':
71
"""
72
Implements OR operator (|) for combining comparisons.
73
74
Args:
75
other: Another DirtyEquals instance to combine with
76
77
Returns:
78
DirtyOr: Combined comparison that passes if either comparison passes
79
"""
80
81
def __and__(self, other: 'DirtyEquals') -> 'DirtyAnd':
82
"""
83
Implements AND operator (&) for combining comparisons.
84
85
Args:
86
other: Another DirtyEquals instance to combine with
87
88
Returns:
89
DirtyAnd: Combined comparison that passes only if both comparisons pass
90
"""
91
92
def __invert__(self) -> 'DirtyNot':
93
"""
94
Implements NOT operator (~) for negating comparisons.
95
96
Returns:
97
DirtyNot: Negated comparison that passes when original fails
98
"""
99
```
100
101
#### Usage Examples
102
103
```python
104
from dirty_equals import IsPositive, IsInt, IsStr
105
106
# Basic usage - all dirty-equals types inherit from DirtyEquals
107
assert 42 == IsPositive
108
109
# Boolean logic with operators
110
assert 42 == (IsInt & IsPositive) # AND: must be both int and positive
111
assert "test" == (IsStr | IsInt) # OR: can be either string or int
112
assert 42 == ~IsNegative # NOT: not negative (i.e., positive or zero)
113
114
# Accessing the last compared value
115
comparison = IsPositive
116
result = (42 == comparison)
117
print(comparison.value) # 42 - the last value that was compared
118
```
119
120
### AnyThing
121
122
A comparison class that matches any value whatsoever. Always returns `True` regardless of the input, useful for placeholder comparisons or when you need to accept any value in a structure.
123
124
```python { .api }
125
class AnyThing(DirtyEquals):
126
"""
127
Matches any value - always returns True.
128
129
Useful as a placeholder when you want to accept any value in a comparison,
130
particularly in data structures where some fields can be anything.
131
"""
132
133
def equals(self, other: Any) -> bool:
134
"""
135
Always returns True regardless of the input value.
136
137
Args:
138
other: Any value (ignored)
139
140
Returns:
141
bool: Always True
142
"""
143
```
144
145
#### Usage Examples
146
147
```python
148
from dirty_equals import AnyThing, IsDict
149
150
# Accept any value
151
assert 42 == AnyThing
152
assert "hello" == AnyThing
153
assert [1, 2, 3] == AnyThing
154
assert {"key": "value"} == AnyThing
155
assert None == AnyThing
156
157
# Useful in data structure validation
158
user_data = {
159
'id': 123,
160
'name': 'John',
161
'metadata': {'created': '2023-01-01', 'source': 'api'}
162
}
163
164
# Check structure but accept any metadata
165
assert user_data == {
166
'id': 123,
167
'name': 'John',
168
'metadata': AnyThing # Accept any metadata value
169
}
170
171
# In partial dictionary checking
172
from dirty_equals import IsPartialDict, IsPositive
173
174
assert user_data == IsPartialDict({
175
'id': IsPositive,
176
'metadata': AnyThing
177
})
178
```
179
180
### IsOneOf
181
182
Checks that a value equals one of the provided expected values. Useful for validating that a value matches any one of several acceptable options.
183
184
```python { .api }
185
class IsOneOf(DirtyEquals):
186
"""
187
Checks that value equals one of the given expected values.
188
189
Performs equality checking against each expected value until a match is found.
190
"""
191
192
def __init__(self, expected_value: Any, *more_expected_values: Any):
193
"""
194
Initialize with expected values to match against.
195
196
Args:
197
expected_value: First expected value
198
*more_expected_values: Additional expected values
199
"""
200
201
@property
202
def expected_values(self) -> Tuple[Any, ...]:
203
"""
204
Get tuple of all expected values.
205
206
Returns:
207
Tuple containing all expected values to match against
208
"""
209
210
def equals(self, other: Any) -> bool:
211
"""
212
Check if other equals any of the expected values.
213
214
Args:
215
other: Value to check
216
217
Returns:
218
bool: True if other equals any expected value
219
"""
220
```
221
222
#### Usage Examples
223
224
```python
225
from dirty_equals import IsOneOf
226
227
# Basic usage - check for multiple possible values
228
assert 'red' == IsOneOf('red', 'green', 'blue')
229
assert 'blue' == IsOneOf('red', 'green', 'blue')
230
assert 42 == IsOneOf(1, 42, 100)
231
232
# Works with different types
233
assert 'active' == IsOneOf('active', 1, True, 'enabled')
234
assert True == IsOneOf('active', 1, True, 'enabled')
235
236
# In data validation
237
status_codes = [200, 201, 202]
238
response_code = 201
239
assert response_code == IsOneOf(*status_codes)
240
241
# With data structures
242
user_role = 'admin'
243
valid_roles = IsOneOf('admin', 'user', 'moderator', 'guest')
244
assert user_role == valid_roles
245
246
# In complex validations
247
user_data = {
248
'status': 'active',
249
'role': 'admin',
250
'priority': 1
251
}
252
253
assert user_data == {
254
'status': IsOneOf('active', 'pending', 'suspended'),
255
'role': IsOneOf('admin', 'user', 'moderator'),
256
'priority': IsOneOf(1, 2, 3, 4, 5)
257
}
258
259
# Access expected values
260
role_checker = IsOneOf('admin', 'user', 'moderator')
261
print(role_checker.expected_values) # ('admin', 'user', 'moderator')
262
```
263
264
## Type Definitions
265
266
```python { .api }
267
from typing import Any, Tuple
268
269
class DirtyEqualsMeta(type):
270
"""Metaclass for DirtyEquals with operator overloading support."""
271
272
class DirtyOr(DirtyEquals):
273
"""Combination of two DirtyEquals with OR logic."""
274
275
class DirtyAnd(DirtyEquals):
276
"""Combination of two DirtyEquals with AND logic."""
277
278
class DirtyNot(DirtyEquals):
279
"""Negation of a DirtyEquals comparison."""
280
281
__version__: str
282
"""Package version string (e.g., '0.9.0')."""
283
```