Custom Types¶
DirtyEquals ¶
Bases: Generic[T]
Base type for all dirty-equals types.
value
property
¶
__init__ ¶
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*repr_args |
Any
|
unnamed args to be used in |
()
|
**repr_kwargs |
Any
|
named args to be used in |
{}
|
equals ¶
Abstract method, must be implemented by subclasses.
TypeError
and ValueError
are caught in __eq__
and indicate other
is not equals to this type.
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