OpType is a Python library (v0.17.0) providing building blocks for precise and flexible type hints, offering single-method protocols for dunder methods, exact types that reject sneaky subtypes, and typed operators. It aims to make type-checking more robust and expressive. The library is actively maintained with somewhat frequent minor releases and supports various modern type checkers like mypy, pyright, and pyrefly.
pip install optypeVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to define a function `twice` that accepts any type `x` for which `2 * x` is valid, using `optype.CanRMul` for precise type hinting. It also shows a more flexible version using `CanMul` as a fallback, leveraging `isinstance` due to `optype` protocols being runtime-checkable.
Review the specific `Can*` protocols affected and adjust type parameter usage according to the updated documentation or remove redundant parameters.
Remove the generic type parameter from `HasDataclassFields` usage. For example, change `HasDataclassFields[T]` to `HasDataclassFields`.
Install with `pip install optype[numpy]` or explicitly `pip install numpy-typing-compat` alongside `optype`.
Use `optype` protocols for type checking and runtime `isinstance` checks, but inherit from standard ABCs or implement methods directly in your classes rather than inheriting from `optype.Can*` protocols.
Install the library using pip: `pip install optype`
Install the missing dependency: `pip install typing_extensions`
Ensure that the value passed to the `optype.Exact` annotation is of the exact specified type, not a subtype. If a subtype is acceptable, use `BaseClass` directly or `typing.Union` instead of `optype.Exact`.
Modify `MyObject` to implement the `__add__` dunder method with a signature compatible with `optype.CanAdd[int, int]`, or pass an object that already satisfies the `optype.CanAdd` protocol.