OpType

0.17.0 · active · verified Fri Apr 10

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.

Warnings

Install

Imports

Quickstart

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.

from typing import Literal, TypeVar
from optype import CanMul, CanRMul

Y = TypeVar('Y')
Two: Literal[2] = 2

def twice(x: CanRMul[Literal[2], Y]) -> Y:
    return Two * x

# Example usage with different types
print(f"twice(2) = {twice(2)}")
print(f"twice(3.14) = {twice(3.14)}")
print(f"twice('I') = {twice('I')}")

# Fallback for types that implement __mul__ but not __rmul__
def twice_flexible(x: CanRMul[Literal[2], Y] | CanMul[Literal[2], Y]) -> Y:
    if isinstance(x, CanRMul):
        return Two * x
    else:
        return x * Two

print(f"twice_flexible(5) = {twice_flexible(5)}")

view raw JSON →