Custom Types¶
Custom Type Example¶
To demonstrate the use of custom types, we'll create a custom type that matches any even number.
We won't inherit from IsNumeric
in this case to keep the example simple.
IsEven
from decimal import Decimal
from typing import Any, Union
from dirty_equals import DirtyEquals, IsOneOf
class IsEven(DirtyEquals[Union[int, float, Decimal]]):
def equals(self, other: Any) -> bool:
return other % 2 == 0
assert 2 == IsEven
assert 3 != IsEven
assert 'foobar' != IsEven
assert 3 == IsEven | IsOneOf(3)
There are a few advantages of inheriting from DirtyEquals
compared to just
implementing your own class with an __eq__
method:
TypeError
andValueError
inequals
are caught and result in a not-equals result.- A useful
__repr__
is generated, and modified if the==
operation returnsTrue
, see pytest compatibility - boolean logic works out of the box
- Uninitialised usage
(
IsEven
rather thanIsEven()
) works out of the box