Skip to content

Custom Types

DirtyEquals

Bases: Generic[T]

Base type for all dirty-equals types.

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:

.values
from dirty_equals import IsStr

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

print(token_is_str.value)
#> t-123

__init__

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

Parameters:

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

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.

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:

  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