Ensure

1.0.4 · active · verified Sun Apr 12

Ensure is a Python library offering a set of simple, literate assertion helpers for validating conditions. It allows writing expressive, concise, and readable Pythonic code for validation, inspired by JavaScript assertion libraries. Beyond testing, 'ensure' can be used for production code validation as it doesn't rely on the 'assert' statement (which can be disabled with the -O flag). The current version is 1.0.4, and it is actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates core `ensure` functionalities: basic type and value assertions, chained property checks, function call validation (including expected return values and raised exceptions), and the use of `check` for custom exception types. It also shows how to apply `ensure_annotations` for runtime type checking in functions.

from ensure import ensure, check

# Basic assertions
ensure(1).is_an(int)
ensure("hello").is_a(str).has_length(5)
ensure([1, 2, 3]).contains(1).and_also.does_not_contain(4)

# Chained assertions
ensure({"a": 1, "b": 2}).has_key("a").whose_value.is_an(int)

# Function call assertions
ensure(int).called_with("1100101", base=2).returns(101)
ensure(dict).called_with(1, 2).raises(TypeError)

# Using 'check' for custom exception handling
try:
    check(1).is_a(float).or_raise(ValueError, "Value must be a float, got {value}")
except ValueError as e:
    print(f"Caught expected error: {e}")

# Type annotation enforcement (Python 3)
from ensure import ensure_annotations, EnsureError

@ensure_annotations
def add_numbers(a: int, b: int) -> int:
    return a + b

print(f"2 + 3 = {add_numbers(2, 3)}")

# This would typically raise an EnsureError
try:
    add_numbers("2", 3)
except EnsureError as e:
    print(f"Caught expected annotation error: {e}")

view raw JSON →