Skip to content

Custom Types


Bases: Generic[T]

Base type for all dirty-equals types.


__init__(*repr_args: Any, **repr_kwargs: Any)


Name Type Description Default
*repr_args Any

unnamed args to be used in __repr__

**repr_kwargs Any

named args to be used in __repr__



equals(other: Any) -> bool

Abstract method, must be implemented by subclasses.

TypeError and ValueError are caught in __eq__ and indicate other is not equals to this type.

value property

value() -> T

Property to get the value last successfully compared to this object.

This is seldom very useful, put it's provided for completeness.

Example of usage:

from dirty_equals import IsStr

token_is_str = IsStr(regex=r't-.+')
assert 't-123' == token_is_str

#> 't-123'

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.

from decimal import Decimal
from typing import Any, Union
from dirty_equals import IsOneOf
from dirty_equals import DirtyEquals

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:

  1. TypeError and ValueError in equals are caught and result in a not-equals result.
  2. A useful __repr__ is generated, and modified if the == operation returns True, see pytest compatibility
  3. boolean logic works out of the box
  4. Uninitialised usage (IsEven rather than IsEven()) works out of the box