| 1 |
# Custom Types |
| 2 |
|
| 3 |
::: dirty_equals._base.DirtyEquals |
| 4 |
options: |
| 5 |
merge_init_into_class: false |
| 6 |
|
| 7 |
## Custom Type Example |
| 8 |
|
| 9 |
To demonstrate the use of custom types, we'll create a custom type that matches any even number. |
| 10 |
|
| 11 |
We won't inherit from [`IsNumeric`][dirty_equals.IsNumeric] in this case to keep the example simple. |
| 12 |
|
| 13 |
```py title="IsEven" |
| 14 |
from decimal import Decimal |
| 15 |
from typing import Any, Union |
| 16 |
|
| 17 |
from dirty_equals import DirtyEquals, IsOneOf |
| 18 |
|
| 19 |
|
| 20 |
class IsEven(DirtyEquals[Union[int, float, Decimal]]): |
| 21 |
def equals(self, other: Any) -> bool: |
| 22 |
return other % 2 == 0 |
| 23 |
|
| 24 |
|
| 25 |
assert 2 == IsEven |
| 26 |
assert 3 != IsEven |
| 27 |
assert 'foobar' != IsEven |
| 28 |
assert 3 == IsEven | IsOneOf(3) |
| 29 |
``` |
| 30 |
|
| 31 |
There are a few advantages of inheriting from [`DirtyEquals`][dirty_equals.DirtyEquals] compared to just |
| 32 |
implementing your own class with an `__eq__` method: |
| 33 |
|
| 34 |
1. `TypeError` and `ValueError` in `equals` are caught and result in a not-equals result. |
| 35 |
2. A useful `__repr__` is generated, and modified if the `==` operation returns `True`, |
| 36 |
see [pytest compatibility](../usage.md#__repr__-and-pytest-compatibility) |
| 37 |
3. [boolean logic](../usage.md#boolean-logic) works out of the box |
| 38 |
4. [Uninitialised usage](../usage.md#initialised-vs-class-comparison) |
| 39 |
(`IsEven` rather than `IsEven()`) works out of the box |