PyHamcrest is a framework for writing matcher objects for Python. It provides a declarative way to define 'match' rules, most commonly used in unit testing to create flexible and precise assertions. It is currently at version 2.1.0 and has a consistent release cadence with several minor and major updates over the years, most recently adding features for async futures.
pip install pyhamcrestVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates basic usage of `assert_that` with `equal_to` for object comparison and `greater_than` for numeric comparison. PyHamcrest matchers provide a more readable and flexible way to express assertions in tests.
Upgrade to Python 3.6+ or pin PyHamcrest to version <1.9.0 for older Python environments.
Explicitly use `equal_to()` for value comparisons (e.g., `assert_that(actual, equal_to(expected))` instead of `assert_that(actual, expected)`) to ensure consistent behavior across versions.
Avoid using the `numpy alias`. If your code depends on specific NumPy-related matchers, ensure you are using the correct, explicit imports and patterns as per current documentation.
Use `assert_that(calling(your_function), raises(YourException))`.
Design custom matchers to be immutable and stateless, or create new instances for each assertion if state management is unavoidable.
Ensure `pyhamcrest` is installed via `pip install PyHamcrest` and import matchers explicitly or using a wildcard from `hamcrest` like `from hamcrest import assert_that, equal_to` or `from hamcrest.library.object import equal_to`.
Import the specific matchers you need, for example: `from hamcrest import assert_that, is_, equal_to` or `from hamcrest import *` to import all top-level matchers.
For asserting exceptions within `pytest` tests, it's generally recommended to use `pytest.raises` as a context manager: `with pytest.raises(SomeException): your_function_that_raises()` or use PyHamcrest's `calling` matcher with `raises` for more flexible checks: `assert_that(calling(your_function).with_args(arg1), raises(SomeException))`.
If you want to assert that a sequence contains specific items, use `has_item` or `has_items`: `assert_that(my_list, has_item(expected_item))` or `assert_that(my_list, has_items(item1, item2))`.