### Install OpType with Development Tools Source: https://github.com/jorenham/optype/blob/master/_autodocs/README.md Install optype with development tools using pip. ```bash pip install optype[dev] ``` -------------------------------- ### Install Optype via PyPI Source: https://github.com/jorenham/optype/blob/master/docs/installation.md Use this command to install the base Optype package from PyPI. ```shell pip install optype ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/jorenham/optype/blob/master/CONTRIBUTING.md Installs all necessary dependencies for running linters, type-checkers, and unit tests. ```bash uv sync ``` -------------------------------- ### Install OpType with NumPy Support Source: https://github.com/jorenham/optype/blob/master/_autodocs/README.md Install optype with optional NumPy support using pip. ```bash pip install optype[numpy] ``` -------------------------------- ### Install Optype for Development Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Install optype with development tools using pip or uv. Optional dependency groups like 'lint', 'test', 'type', and 'doc' can be specified. ```bash pip install optype[dev] # or with specific groups: pip install optype[lint,test,type,doc] ``` -------------------------------- ### Examples of Can* Protocols Source: https://github.com/jorenham/optype/blob/master/docs/getting-started.md Provides examples of optype's Can* protocols, which describe the capabilities of operations like abs(), addition, and item access. ```python import optype as op from typing import Literal type Two = Literal[2] type RMul2[R] = op.CanRMul[Two, R] type Mul2[R] = op.CanMul[Two, R] type CMul2[R] = Mul2[R] | RMul2[R] _: op.CanAbs[int] = 42 # abs(42) -> int _: op.CanAdd[str, str] = "hi" # "hi" + "hi" -> str _: op.CanGetitem[int, int] = [1] # [1][0] -> int ``` -------------------------------- ### Install Optype Base Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Install the core optype library using pip or uv. Requires Python 3.12+ and typing-extensions for older Python versions. ```bash pip install optype # or uv add optype ``` -------------------------------- ### Build Documentation with Zensical Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Command to build project documentation using Zensical. Ensure you have Zensical installed via uv. ```bash uv run -m zensical build ``` -------------------------------- ### Install Optype with NumPy Support Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Install optype with optional NumPy support using pip or uv. This requires specific versions of numpy and numpy-typing-compat. ```bash pip install optype[numpy] # or uv add optype[numpy] ``` -------------------------------- ### Validate Lefthook Setup Source: https://github.com/jorenham/optype/blob/master/CONTRIBUTING.md Verifies that the lefthook installation and configuration are correct. ```bash $ uvx lefthook validate All good ``` -------------------------------- ### Install Optype with NumPy Support via PyPI Source: https://github.com/jorenham/optype/blob/master/docs/installation.md Install Optype with optional NumPy support by specifying the 'numpy' extra. This ensures compatibility with NumPy and numpy-typing-compat. ```shell pip install "optype[numpy]" ``` -------------------------------- ### Install Optype via Conda Source: https://github.com/jorenham/optype/blob/master/docs/installation.md Install Optype from the conda-forge channel using the conda package manager. ```shell conda install conda-forge::optype ``` -------------------------------- ### Install Git Hooks with Lefthook Source: https://github.com/jorenham/optype/blob/master/CONTRIBUTING.md Installs the git hooks managed by lefthook, including post-checkout, post-merge, and pre-commit hooks. ```bash $ uvx lefthook install sync hooks: ✔️ (post-checkout, post-merge, pre-commit) ``` -------------------------------- ### Install Lefthook Source: https://github.com/jorenham/optype/blob/master/CONTRIBUTING.md Installs the lefthook tool for managing Git hooks, which automatically lints and formats code before commits. ```bash $ uv tool install lefthook --upgrade Resolved 1 package in 139ms Audited 1 package in 0.00ms Installed 1 executable: lefthook ``` -------------------------------- ### CanAdd Protocol Example Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/can-protocols.md Demonstrates how to implement and use the `CanAdd` protocol for objects supporting the addition operator `+`. This example shows a `Vector` class that can be added to another `Vector` instance. ```python import optype as op class Vector: def __init__(self, x: float, y: float): self.x = x self.y = y def __add__(self, other: 'Vector') -> 'Vector': return Vector(self.x + other.x, self.y + other.y) v1 = Vector(1, 2) v2 = Vector(3, 4) if isinstance(v1, op.CanAdd): v3 = v1 + v2 # Vector(4, 6) ``` -------------------------------- ### Type Inference Examples with Optype Source: https://github.com/jorenham/optype/blob/master/docs/getting-started.md Demonstrates how the optype-annotated `twice` function correctly infers types for various inputs. ```python twice(2) # -> int twice(3.14) # -> float twice("I") # -> str (because 'I' * 2 == 'II') twice(True) # -> int (because 2 * True == 2) twice((42, True)) # -> tuple[Literal[42, True], ...] ``` -------------------------------- ### Install Optype-NumPy via Conda Source: https://github.com/jorenham/optype/blob/master/docs/installation.md Install the optype-numpy package from conda-forge for NumPy support when using Conda. ```shell conda install conda-forge::optype-numpy ``` -------------------------------- ### Custom MyPy Plugin for Optype Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Example of a user-defined MyPy plugin to integrate custom hooks for Optype methods. This requires defining a class that inherits from mypy.plugin.Plugin. ```python from typing import Type from mypy.plugin import Plugin class OptypePlugin(Plugin): def get_method_hook(self, fullname: str): # Custom hooks for optype methods pass ``` -------------------------------- ### Using JustObject for Exact Object Type Checking Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/just.md Illustrates how to use JustObject to check if a value is exactly an object instance, useful for typing specific object sentinels. This example shows how to verify if a value is the exact sentinel object. ```python import optype as op sentinel = object() def is_sentinel(value: object) -> bool: """Check if value is exactly this sentinel.""" return isinstance(value, op.JustObject) and value is sentinel is_sentinel(sentinel) # True is_sentinel(object()) # False (different instance) ``` -------------------------------- ### Scalar Usage Examples Source: https://github.com/jorenham/optype/blob/master/docs/reference/numpy/scalar.md Demonstrates how to use the Scalar interface to type hint specific NumPy scalar types with their Python type and item size. ```python are_birds_real: Scalar[bool, Literal[1]] = np.bool(True) the_answer: Scalar[int, Literal[2]] = np.uint16(42) alpha: Scalar[float, Literal[8]] = np.float64(1 / 137) ``` -------------------------------- ### Get Item from Container Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/operators.md Retrieves an item from a container using a key or index. Supports dictionary-like and list-like objects. Requires importing the optype library. ```python import optype as op data = {"a": 1, "b": 2} value = op.do_getitem(data, "a") # 1 lst = [10, 20, 30] item = op.do_getitem(lst, 1) # 20 ``` -------------------------------- ### Infer type signature using `optype infer` Source: https://github.com/jorenham/optype/blob/master/docs/index.md The `optype infer` command can automatically derive type signatures from lambda functions. This example shows how to infer the signature for a function equivalent to `lambda x: 2 * x`, which results in `[R](x: CanRMul[Literal[2], R]) -> R`. ```console $ optype infer "lambda x: 2 * x" [R](x: CanRMul[Literal[2], R]) -> R ``` -------------------------------- ### Build Distribution with UV Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Build the project distribution using the `uv build` command. ```bash uv build ``` -------------------------------- ### Project File Structure Source: https://github.com/jorenham/optype/blob/master/_autodocs/README.md Illustrates the directory layout for the optype project's documentation and source files. ```bash output/ ├── README.md # This file ├── index.md # Main API reference overview ├── types.md # Type definitions and aliases ├── configuration.md # Configuration and environment └── api-reference/ ├── README.md # Navigation guide ├── just.md # Invariant type protocols ├── can-protocols.md # Capability protocols ├── operators.md # Operator functions └── has-protocols.md # Attribute protocols ``` -------------------------------- ### UV Build Backend Configuration Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Configure the UV build backend, specifying required packages and the build backend itself in `pyproject.toml`. Also sets the module root for the build. ```toml [build-system] requires = ["uv_build>=0.11.19,<0.12.0"] build-backend = "uv_build" [tool.uv.build-backend] module-root = "" ``` -------------------------------- ### Generating Compatible Python Stub File Source: https://github.com/jorenham/optype/blob/master/docs/infer.md Use the `--format compat` option with the `optype infer` command to generate a self-contained, type-checkable `.pyi` stub file instead of a terse signature. ```console $ optype infer --format compat "lambda x, y: x * y" from typing import overload from optype import CanMul, CanRMul @overload def f[T, R](x: CanMul[T, R], y: T) -> R: ... @overload def f[T, R](x: T, y: CanRMul[T, R]) -> R: ... ``` -------------------------------- ### Importing from Main Module Source: https://github.com/jorenham/optype/blob/master/_autodocs/index.md Demonstrates the standard way to import symbols from the main 'optype' module, aliasing it as 'op' for convenience. ```python import optype as op # Access main classes just_int_val: op.JustInt = 42 can_add_obj: op.CanAdd = 5 # Access functions result = op.do_add(1, 2) ``` -------------------------------- ### do_anext Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/operators.md Gets the next item from an asynchronous iterator. ```APIDOC ## do_anext ### Description Gets the next item from an asynchronous iterator. ``` -------------------------------- ### Generate compat backend signature Source: https://github.com/jorenham/optype/blob/master/docs/reference/experimental/infer.md Use `backend="compat"` to render the inferred signature as a self-contained, type-checkable stub file. This format includes necessary imports and synthesized Protocols. ```console $ optype infer --format compat "lambda x: x + 1" from typing import Literal from optype import CanAdd def f[R](x: CanAdd[Literal[1], R]) -> R: ... ``` -------------------------------- ### "compat" backend Source: https://github.com/jorenham/optype/blob/master/docs/reference/experimental/infer.md Renders the inferred signature using the "compat" backend, producing a self-contained, type-checkable .pyi-style stub that includes necessary imports and definitions. ```APIDOC ## `"compat"` `backend="compat"` (or `--format compat` on the command line) renders the result as a self-contained, type-checkable `.pyi`-style stub: imports, any synthesized helper `Protocol`s, and `@overload`-decorated `def`s. ```console $ optype infer --format compat "lambda x: x + 1" from typing import Literal from optype import CanAdd def f[R](x: CanAdd[Literal[1], R]) -> R: ... ``` Constructs the typing spec cannot express are lowered: an intersection or the inline `Has['name', T]` form becomes a `Protocol`, a typevar-referencing bound becomes a (possibly self-referential) `Protocol`, and the `~` complement is dropped. A few inferences still fall outside the type system, such as a non-generic protocol read as generic, or a same-attribute intersection. ``` -------------------------------- ### __getstate__ Source: https://github.com/jorenham/optype/blob/master/docs/reference/stdlib/pickle.md This method is called to get the state of an object to be pickled. The returned value should be picklable. ```APIDOC ## __getstate__ ### Description Returns the state of the object to be pickled. ### Signature `() -> S` ### Type `CanGetstate[+S]` ``` -------------------------------- ### Compare optype.string PRINTABLE with string.printable Source: https://github.com/jorenham/optype/blob/master/docs/reference/stdlib/string.md Demonstrates the equivalence between optype.string.PRINTABLE and string.printable by joining the tuple and comparing it to the original string. ```python import string import optype as opt print("".join(opt.string.PRINTABLE) == string.printable) print(tuple(string.printable) == opt.string.PRINTABLE) ``` -------------------------------- ### __reduce__ Source: https://github.com/jorenham/optype/blob/master/docs/reference/stdlib/pickle.md This method is called by pickle to get a representation of the object that can be pickled. It should return a string or a tuple. ```APIDOC ## __reduce__ ### Description Returns a picklable representation of the object. ### Signature `() -> R` ### Type `CanReduce[+R: str | tuple =]` ``` -------------------------------- ### do_getitem Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/operators.md Gets an item from a container using a key or index. This is equivalent to `value = obj[key]`. ```APIDOC ## do_getitem ### Signature ```python @overload def do_getitem[KT, VT, DT]( obj: CanGetMissing[KT, VT, DT], key: KT, /, ) -> VT | DT: ... @overload def do_getitem[KT, VT](obj: CanGetitem[KT, VT], key: KT, /) -> VT: ... def do_getitem[KT, VT, DT]( obj: CanGetitem[KT, VT] | CanGetMissing[KT, VT, DT], key: KT, /, ) -> VT | DT: """Same as `value = obj[key]`.""" return obj[key] ``` ### Description Gets an item from a container using a key or index. ### Example ```python import optype as op data = {"a": 1, "b": 2} value = op.do_getitem(data, "a") # 1 lst = [10, 20, 30] item = op.do_getitem(lst, 1) # 20 ``` ``` -------------------------------- ### Implementing CanEq Protocol for Custom Class Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/can-protocols.md Demonstrates how to implement the CanEq protocol for a custom 'Version' class to support equality checks. Ensure the class implements the __eq__ method. ```python import optype as op class Version: def __init__(self, major: int, minor: int): self.major = major self.minor = minor def __eq__(self, other: object) -> bool: if not isinstance(other, Version): return NotImplemented return self.major == other.major and self.minor == other.minor v1 = Version(1, 0) v2 = Version(1, 0) if isinstance(v1, op.CanEq): result = v1 == v2 # True ``` -------------------------------- ### do_getattr Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/operators.md Gets an attribute from an object. It supports an optional default value to return if the attribute does not exist. ```APIDOC ## do_getattr ### Description Gets an attribute from an object. ### Signature ```python def do_getattr(obj: CanGetattr, name: str, /) -> object: ... def do_getattr(obj: CanGetattr, name: str, default: object, /) -> object: ... ``` ### Example ```python import optype as op class Person: def __init__(self, name): self.name = name p = Person("Alice") name = op.do_getattr(p, "name") # "Alice" age = op.do_getattr(p, "age", None) # None (default) ``` ``` -------------------------------- ### do_next Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/operators.md Gets the next item from an iterator. It can also accept a default value to return if the iterator is exhausted. ```APIDOC ## do_next ### Description Gets the next item from an iterator. It can also accept a default value to return if the iterator is exhausted. ### Signature ```python @overload def do_next[ValT](iterator: CanNext[ValT], /) -> ValT: ... @overload def do_next[ValT, DefaultT]( iterator: CanNext[ValT], default: DefaultT, /, ) -> ValT | DefaultT: ... ``` ### Example ```python import optype as op it = iter([1, 2, 3]) first = op.do_next(it) # 1 second = op.do_next(it) # 2 third = op.do_next(it) # 3 default = op.do_next(it, None) # None (iterator exhausted) ``` ``` -------------------------------- ### Format Documentation with Dprint Source: https://github.com/jorenham/optype/blob/master/CONTRIBUTING.md Formats the markdown documentation files using the dprint tool. ```bash uv run dprint fmt ``` -------------------------------- ### Access Optype Version Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Import the Optype library and print its version attribute. ```python import optype print(optype.__version__) # "0.18.0" ``` -------------------------------- ### Checking Attributes with Has Protocols Source: https://github.com/jorenham/optype/blob/master/_autodocs/index.md Use Has protocols to check for the presence of specific attributes on an object. This example checks for name, docstring, and annotations. ```python import optype as op def describe(obj: object) -> None: """Print details about an object.""" if isinstance(obj, op.HasName): print(f"Name: {obj.__name__}") if isinstance(obj, op.HasDoc): print(f"Doc: {obj.__doc__}") if isinstance(obj, op.HasAnnotations): print(f"Annotations: {obj.__annotations__}") describe(int) # Prints: Name: int, Doc: ..., Annotations: {} ``` -------------------------------- ### Checking for Attributes at Runtime Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/has-protocols.md Demonstrates how to use `isinstance` with various `optype` protocols to check for the presence of specific attributes like `__name__`, `__doc__`, `__dict__`, and `__annotations__` on an object. ```APIDOC ## Checking for Attributes at Runtime ```python import optype as op def inspect_object(obj: object) -> None: if isinstance(obj, op.HasName): print(f"Name: {obj.__name__}") if isinstance(obj, op.HasDoc): print(f"Docstring: {obj.__doc__}") if isinstance(obj, op.HasDict): print(f"Instance dict: {obj.__dict__}") if isinstance(obj, op.HasAnnotations): print(f"Annotations: {obj.__annotations__}") ``` ``` -------------------------------- ### Get Attribute with Default Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/operators.md Retrieves an attribute from an object, returning a default value if the attribute does not exist. Requires importing the optype library. ```python import optype as op class Person: def __init__(self, name): self.name = name p = Person("Alice") name = op.do_getattr(p, "name") # "Alice" age = op.do_getattr(p, "age", None) # None (default) ``` -------------------------------- ### Get Length of Container Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/operators.md Returns the number of items in a container. Works with lists, strings, and other sequence types. Requires importing the optype library. ```python import optype as op length = op.do_len([1, 2, 3]) # 3 length = op.do_len("hello") # 5 ``` -------------------------------- ### Runtime Type Checking with Optype Protocols Source: https://github.com/jorenham/optype/blob/master/docs/reference/index.md Demonstrates how to use isinstance() with optype protocols for runtime type checking. This is useful for verifying if an object conforms to a specific protocol. ```python import optype as op isinstance("hello", op.CanAdd) # True isinstance(42, op.CanAbs) # True isinstance([1], op.CanGetitem) # True ``` -------------------------------- ### Get Next Iterator Item with do_next Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/operators.md Retrieves the next item from an iterator. It can also accept a default value to return if the iterator is exhausted. ```python import optype as op it = iter([1, 2, 3]) first = op.do_next(it) # 1 second = op.do_next(it) # 2 third = op.do_next(it) # 3 default = op.do_next(it, None) # None (iterator exhausted) ``` -------------------------------- ### Basic Python Function Source: https://github.com/jorenham/optype/blob/master/docs/getting-started.md A simple Python function to demonstrate basic implementation. ```python def twice(x): return 2 * x ``` -------------------------------- ### Enable Ruff Formatting Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Set an environment variable to enable Ruff's formatting capabilities. ```bash export RUFF_FORMAT=true ``` -------------------------------- ### __getnewargs_ex__ and __new__ Source: https://github.com/jorenham/optype/blob/master/docs/reference/stdlib/pickle.md These methods are used to reconstruct an object using its constructor with both positional and keyword arguments. ```APIDOC ## __getnewargs_ex__ and __new__ ### Description Used to reconstruct an object with positional and keyword arguments. ### Signatures `__getnewargs_ex__(): tuple[tuple[V, ...], dict[str, KV]]` `__new__(*tuple[V, ...], **dict[str, KV]) -> Self` ### Type `CanGetnewargsEx[+V, ~KV]` ``` -------------------------------- ### Type-Safe Operator Dispatch Source: https://github.com/jorenham/optype/blob/master/_autodocs/index.md Provides an example of type-safe operator dispatch using generic functions and 'op.DoesAdd'. This allows operations to be applied to different types safely. ```python import optype as op def apply_operation[T](lhs: T, rhs: T, op_func: op.DoesAdd) -> T: """Apply an operation to two values.""" return op_func(lhs, rhs) result = apply_operation(5, 3, op.do_add) # 8 result = apply_operation("a", "b", op.do_add) # "ab" ``` -------------------------------- ### Runtime Type Checking with JustInt Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/just.md Demonstrates how to use `isinstance` with `JustInt` to narrow down types to exactly `int` at runtime, ensuring that boolean values are not accepted. ```python value: object = 42 if isinstance(value, op.JustInt): # Type narrowed to JustInt (exactly int) reveal_type(value) # int, not bool ``` -------------------------------- ### Inferring Signature for a Lambda Function Source: https://github.com/jorenham/optype/blob/master/docs/infer.md Use the `infer` function to get the inferred signature of a simple lambda function. The output is a terse string representation of the required protocols. ```python >>> from optype.infer import infer >>> infer(lambda x: x + 1) '[R](x: CanAdd[Literal[1], R]) -> R' ``` -------------------------------- ### OpType Exact Type Matching Source: https://github.com/jorenham/optype/blob/master/_autodocs/README.md Demonstrates exact type matching using op.JustInt, ensuring only integers are accepted. ```python import optype as op # Exact type matching (no bool for int) def process_int(x: op.JustInt) -> int: return x * 2 ``` -------------------------------- ### Descriptor Get Interface Source: https://github.com/jorenham/optype/blob/master/docs/reference/core/descriptors.md Defines the interface for descriptor's `__get__` operation when accessing an instance attribute. It specifies the types for the instance, the owner class, and the returned value. ```Python v: V = T().d vt: VT = T.d ``` ```Python v: V = T().d vt: Self = T.d ``` -------------------------------- ### AtLeast1D Type Alias Source: https://github.com/jorenham/optype/blob/master/docs/reference/numpy/shape.md Defines a type alias for shapes with at least 1 dimension. It's a tuple starting with an integer followed by any shape with at least 0 dimensions. ```python type AtLeast1D = (int, *AtLeast0D) ``` -------------------------------- ### Getting Protocol Members with optype.inspect.get_protocol_members Source: https://github.com/jorenham/optype/blob/master/docs/reference/stdlib/inspect.md This function retrieves the public members of a protocol, supporting PEP 695 type aliases and unpacking unions of Literals. It is a more robust alternative to typing.get_protocol_members. ```python # Example usage would go here, but is not provided in the source text. ``` -------------------------------- ### __dlpack_device__ Method Source: https://github.com/jorenham/optype/blob/master/docs/reference/stdlib/dlpack.md The `__dlpack_device__` method returns the device information for DLPack compatibility. ```APIDOC ## __dlpack_device__ Method ### Description Returns the device information for DLPack compatibility. ### Method Signature ```python def __dlpack_device__() -> tuple[T, D]: ... ``` ### Returns - A tuple representing the device type and device ID. ``` -------------------------------- ### Safely Get Object Name with HasName Protocol Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/has-protocols.md Provides a type-safe way to retrieve the __name__ attribute from objects that conform to the HasName protocol. Returns None if the object does not have a __name__. ```python import optype as op from typing import TypeVar, overload T = TypeVar('T') @overload def get_name(obj: op.HasName[str]) -> str: ... @overload def get_name(obj: object) -> None: ... def get_name(obj: object) -> str | None: """Safely get name from objects that have __name__. """ if isinstance(obj, op.HasName): return obj.__name__ return None ``` -------------------------------- ### Dprint Check Command Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Run the dprint check command to verify conventional formatting for the optype project. No specific configuration file is needed as it relies on conventional formatting. ```bash dprint check ``` -------------------------------- ### Generic Protocol Checks Source: https://github.com/jorenham/optype/blob/master/_autodocs/index.md Demonstrates generic protocol checks using 'isinstance' with 'op.CanStr' and 'op.CanRepr' to determine the best serialization method for an object. ```python import optype as op def serialize(obj: object) -> str: """Serialize an object based on its capabilities.""" if isinstance(obj, op.CanStr): return str(obj) elif isinstance(obj, op.CanRepr): return repr(obj) else: return object.__repr__(obj) ``` -------------------------------- ### Type Hinting for NumPy Arrays Source: https://github.com/jorenham/optype/blob/master/docs/getting-started.md Use `optype.numpy` for extensive typing support with NumPy arrays. This example defines a function to normalize a 2D NumPy array of real or complex numbers. ```python import numpy as np import optype.numpy as onp def normalize[T: np.inexact](arr: onp.Array2D[T]) -> onp.Array2D[T]: """Normalize a 2D array of real or complex numbers.""" return arr / np.linalg.norm(arr) ``` -------------------------------- ### Combine Protocols with Intersection Types Source: https://github.com/jorenham/optype/blob/master/docs/getting-started.md Combine multiple protocols using intersection types to create a new protocol that requires all specified capabilities. This example requires a type that supports both addition and multiplication. ```python from typing import Protocol import optype as op class CanAddAndMulIntFloat(op.CanAdd[int, float], op.CanMul[int, float], Protocol): pass def process(x: CanAddAndMulIntFloat) -> float: return (x + 1) * 2 ``` -------------------------------- ### Importing Specific Symbols Source: https://github.com/jorenham/optype/blob/master/_autodocs/index.md Shows how to import only specific symbols (classes and functions) directly from the 'optype' module, reducing namespace pollution. ```python from optype import JustInt, CanAdd, do_add def process(x: JustInt) -> int: return do_add(x, 1) ``` -------------------------------- ### Infer Binary Operator Overloads Source: https://github.com/jorenham/optype/blob/master/docs/infer.md Demonstrates how optype infers overloads for binary operators, showing dispatch to either operand. ```console $ optype infer "lambda x, y: x * y" [T, R](x: CanMul[T, R], y: T) -> R [T, R](x: T, y: CanRMul[T, R]) -> R ``` -------------------------------- ### Runtime Checking for Multiplication Operators Source: https://github.com/jorenham/optype/blob/master/docs/getting-started.md Shows how to use optype protocols with isinstance() for runtime checking of multiplication capabilities, handling both __mul__ and __rmul__. ```python import optype as op from typing import Literal type Two = Literal[2] type RMul2[R] = op.CanRMul[Two, R] type Mul2[R] = op.CanMul[Two, R] type CMul2[R] = Mul2[R] | RMul2[R] def twice2[R](x: CMul2[R]) -> R: if isinstance(x, op.CanRMul): return 2 * x else: return x * 2 ``` -------------------------------- ### Define `twice` function with `optype.CanRMul` Source: https://github.com/jorenham/optype/blob/master/docs/index.md Use `optype.CanRMul[T, R]` to define a type hint for a function that performs a right multiplication by a specific type `T` and returns a type `R`. This example demonstrates how to type a `twice` function that accepts any type supporting `__rmul__` with `Literal[2]` and returns a type `R`. ```python from typing import Literal import optype as op type Two = Literal[2] type RMul2[R] = op.CanRMul[Two, R] def twice[R](x: RMul2[R]) -> R: return 2 * x ``` -------------------------------- ### Ty Configuration for Optype Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Configure Ty in pyproject.toml for type analysis of the optype project. This includes environment settings, source includes, and analysis rules. ```toml [tool.ty.environment] python-platform = "all" [tool.ty.src] include = ["optype"] [tool.ty.analysis] respect-type-ignore-comments = false [tool.ty.rules] unused-ignore-comment = "warn" possibly-unresolved-reference = "error" ``` -------------------------------- ### Runtime Type Checking with isinstance Source: https://github.com/jorenham/optype/blob/master/_autodocs/index.md Shows how to perform runtime type checking using 'isinstance' with 'op.CanInt' to narrow down types for safe conversion to integers. ```python import optype as op value: object = input() if isinstance(value, op.CanInt): # Type narrowed to objects that have __int__() num = int(value) ``` -------------------------------- ### Ruff Linting Configuration Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Configure Ruff for linting the Optype project. Specifies source directories and target Python version, along with enabled and ignored lint rules. ```toml [tool.ruff] src = ["optype"] target-version = "py312" [tool.ruff.lint] select = ["ALL"] ignore = [ "ANN401", # any-type "D", # pydocstyle "FBT", # flake8-boolean-trap ] ``` -------------------------------- ### __reduce_ex__ Source: https://github.com/jorenham/optype/blob/master/docs/reference/stdlib/pickle.md This method is similar to __reduce__ but allows for a version-dependent representation. It takes an integer representing the pickle protocol version. ```APIDOC ## __reduce_ex__ ### Description Returns a picklable representation of the object, considering the pickle protocol version. ### Signature `(CanIndex) -> R` ### Type `CanReduceEx[+R: str | tuple =]` ``` -------------------------------- ### Mypy Configuration for Optype Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Configure Mypy in pyproject.toml to check the optype package. Recommended settings include strict mode and specific error code enablings. ```toml [tool.mypy] packages = ["optype"] strict = true ``` ```toml [tool.mypy] # Optype is fully typed disallow_any_expr = false disallow_any_decorated = false disallow_any_explicit = false warn_return_any = false # Enabled error codes enable_error_code = [ "exhaustive-match", "ignore-without-code", "redundant-expr", "truthy-bool", ] ``` -------------------------------- ### Infer Combined Protocol for Sequence Operations Source: https://github.com/jorenham/optype/blob/master/docs/infer.md Demonstrates optype inferring a combined protocol (CanSequence) for operations involving sequence-like behavior. ```console $ optype infer "lambda x, i: x[i] if len(x) else None" [T, R](x: CanSequence[T, R], i: T) -> R | None ``` -------------------------------- ### Lazy Imports with Submodules Source: https://github.com/jorenham/optype/blob/master/_autodocs/index.md Illustrates lazy importing of submodules within 'optype'. Submodules are only imported when they are first accessed, improving initial load times. ```python import optype as op # Lazy load submodules numpy_module = op.numpy # Import on first access types_module = op.types ``` -------------------------------- ### Import Optype NumPy Module Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Import the NumPy specific module from optype. ```python import optype.numpy as onp ``` -------------------------------- ### Run Tox Test Environments Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Commands to execute specific test environments using Tox. This includes testing against different Python versions and static analysis tools like MyPy, Pyright, and Ruff. ```bash tox -e 3.12 # Python 3.12 ``` ```bash tox -e 3.13 # Python 3.13 ``` ```bash tox -e mypy # MyPy checking ``` ```bash tox -e pyright # Pyright checking ``` ```bash tox -e ruff # Ruff linting ``` -------------------------------- ### Pytest Configuration Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Configure pytest options, including test paths, additional arguments, doctest flags, and warning filters in `pyproject.toml`. ```toml [tool.pytest.ini_options] minversion = "9.0" testpaths = ["optype", "tests"] addopts = ["-ra", "--doctest-modules"] doctest_optionflags = [ "NORMALIZE_WHITESPACE", "IGNORE_EXCEPTION_DETAIL", "ELLIPSIS" ] filterwarnings = ["error"] ``` -------------------------------- ### PyRefly Configuration for Optype Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Configure PyRefly in pyproject.toml to enforce strict typing rules for the optype project. ```toml [tool.pyrefly] project-includes = ["optype"] [tool.pyrefly.errors] implicit-abstract-class = "error" implicit-any = "error" implicitly-defined-attribute = "error" missing-override-decorator = "error" not-required-key-access = "error" open-unpacking = "error" unannotated-attribute = "error" unannotated-parameter = "error" unannotated-return = "error" untyped-import = "error" unused-ignore = "error" variance-mismatch = "error" ``` -------------------------------- ### Check for HasDict Protocol Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/has-protocols.md Demonstrates how to check if an object conforms to the HasDict protocol at runtime and access its instance dictionary. ```python import optype as op class FlexibleClass: def __init__(self): self.x = 1 self.y = 2 obj = FlexibleClass() if isinstance(obj, op.HasDict): print(obj.__dict__) # {'x': 1, 'y': 2} obj.__dict__['z'] = 3 print(obj.z) # 3 ``` -------------------------------- ### Verify Optype Typing with BasedPyright Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Use the basedpyright command-line tool to verify that optype has 100% type coverage. ```bash basedpyright --verifytypes optype ``` -------------------------------- ### CanAEnter, CanAExit, CanAEnterSelf, CanAExitSelf Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/can-protocols.md Defines objects that support asynchronous context manager entry and exit operations. ```APIDOC ## CanAEnter, CanAExit, CanAEnterSelf, CanAExitSelf ### Description Objects that support async context manager entry/exit. ``` -------------------------------- ### Runtime Capability Checking with Optype Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/can-protocols.md Use `isinstance` with Optype's capability protocols to check if an object supports specific operations like addition or length retrieval before attempting to use them. This prevents runtime errors. ```python import optype as op def process(obj: object) -> object: if isinstance(obj, op.CanAdd): return obj + obj # Double the value elif isinstance(obj, op.CanLen): return len(obj) # Return length else: return obj # Return as-is ``` -------------------------------- ### JustObject Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/just.md A runtime checkable Just[object] that works on pyright<1.1.390. Useful for typing object() sentinels that must be exactly object instances. ```APIDOC ## JustObject ### Description A runtime checkable `Just[object]`, that also works on `pyright<1.1.390`. Useful for typing `object()` sentinels that must be exactly `object` instances. ### Example ```python import optype as op sentinel = object() def is_sentinel(value: object) -> bool: """Check if value is exactly this sentinel.""" return isinstance(value, op.JustObject) and value is sentinel is_sentinel(sentinel) # True is_sentinel(object()) # False (different instance) ``` ``` -------------------------------- ### Capability Protocols Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/README.md A comprehensive set of over 180 capability protocols covering type conversion, container operations, iteration, arithmetic, comparison, bitwise operations, unary operations, attribute access, reflected operators, augmented assignments, and context managers. ```APIDOC ## Capability Protocols (~180+ protocols) ### Description Provides a wide range of capability protocols for various operations. ### Categories - **Type Conversion**: `CanBool`, `CanInt`, `CanFloat`, `CanComplex`, `CanBytes`, `CanStr` - **Container Operations**: `CanLen`, `CanGetitem`, `CanSetitem`, `CanDelitem`, `CanContains` - **Iteration**: `CanIter`, `CanNext`, `CanAIter`, `CanANext` - **Arithmetic**: `CanAdd`, `CanSub`, `CanMul`, `CanTruediv`, `CanFloordiv`, `CanMod`, `CanPow` - **Comparison**: `CanEq`, `CanNe`, `CanLt`, `CanLe`, `CanGt`, `CanGe` - **Bitwise**: `CanAnd`, `CanOr`, `CanXor`, `CanLshift`, `CanRshift` - **Unary**: `CanAbs`, `CanNeg`, `CanPos`, `CanInvert`, `CanHash`, `CanIndex` - **Attributes**: `CanGetattr`, `CanSetattr`, `CanDelattr` - **Reflected Operators**: `CanRAdd`, `CanRSub`, `CanRMul`, etc. - **Augmented Assignment**: `CanIAdd`, `CanISub`, `CanIMul`, etc. - **Context Managers**: `CanWith`, `CanEnter`, `CanExit`, `CanAsyncWith` ``` -------------------------------- ### Pyright Configuration for Optype Source: https://github.com/jorenham/optype/blob/master/_autodocs/configuration.md Configure Pyright in pyproject.toml for type checking optype. Recommended settings include 'all' type checking mode and specific analysis options. ```toml [tool.pyright] pythonPlatform = "All" typeCheckingMode = "all" ``` ```toml [tool.pyright] # Core settings pythonVersion = "3.12" pythonPlatform = "All" typeCheckingMode = "all" # Optype works best with these enabled enableReachabilityAnalysis = true useLibraryCodeForTypes = false # Less strict settings for better UX reportAny = false reportExplicitAny = false reportPrivateUsage = false reportPrivateImportUsage = false reportUnreachable = false reportUnusedCallResult = false reportUnusedImport = false reportUnusedVariable = false ``` -------------------------------- ### Typed Operator Implementations with do_* Source: https://github.com/jorenham/optype/blob/master/docs/getting-started.md Illustrates optype's do_* types, which provide correctly-typed implementations for operators, like do_abs for the absolute value function. ```python import optype as op # do_abs is a typed version of abs() result = op.do_abs(-5) # -> int ``` -------------------------------- ### Overloaded Function Signatures for Do/Does Source: https://github.com/jorenham/optype/blob/master/_autodocs/types.md Illustrates overloaded function signatures for `do_func`, used for proper type inference with generic parameters and return types. ```python @overload def do_func[ParamT, ReturnT](obj: CanFunc[ParamT, ReturnT], arg: ParamT, /) -> ReturnT: ... @overload def do_func[DefaultT](obj: CanFunc[..., DefaultT], /, default: DefaultT) -> DefaultT: ... ``` -------------------------------- ### __getnewargs__ and __new__ Source: https://github.com/jorenham/optype/blob/master/docs/reference/stdlib/pickle.md These methods are used to reconstruct an object using its constructor with positional arguments. ```APIDOC ## __getnewargs__ and __new__ ### Description Used to reconstruct an object with positional arguments. ### Signatures `__getnewargs__(): tuple[V, ...]` `__new__(V) -> Self` ### Type `CanGetnewargs[+V]` ``` -------------------------------- ### Check for CanGetitem Protocol Conformance Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/can-protocols.md Use `isinstance` with `op.CanGetitem` to verify if an object supports item access via `obj[key]`. This protocol is useful for objects that behave like dictionaries or lists. ```python import optype as op class Config: def __init__(self, data: dict): self.data = data def __getitem__(self, key: str) -> str: return self.data[key] cfg = Config({"api_key": "secret"}) if isinstance(cfg, op.CanGetitem): api_key = cfg["api_key"] # "secret" ``` -------------------------------- ### do_dir Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/operators.md Returns a list of valid attributes for an object. ```APIDOC ## do_dir ### Description Returns a list of valid attributes for an object. ``` -------------------------------- ### Safe Type Conversion with Optype Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/README.md This pattern demonstrates how to safely convert an object to an integer if it supports the CanInt protocol. It returns None if the conversion is not possible. ```python import optype as op def maybe_to_int(obj: object) -> int | None: """Convert to int if possible.""" if isinstance(obj, op.CanInt): return op.do_int(obj) return None ``` -------------------------------- ### Inferring Signature from Command Line (Lambda) Source: https://github.com/jorenham/optype/blob/master/docs/infer.md Use the `optype infer` command to infer the signature of a Python lambda function directly from the command line. The output is a terse signature string. ```console $ optype infer "lambda x: x * 2" [R](x: CanMul[Literal[2], R]) -> R ``` -------------------------------- ### Define JustDate Protocol for datetime.date Source: https://github.com/jorenham/optype/blob/master/_autodocs/types.md This snippet shows how to define a `JustDate` protocol that specifically targets `datetime.date` objects. It requires importing the `datetime` module and defining the protocol using `_JustMeta`. ```python import datetime as dt class JustDate(Protocol, metaclass=_JustMeta, just=dt.date): ... ``` -------------------------------- ### Type-Safe Addition with Optype Source: https://github.com/jorenham/optype/blob/master/_autodocs/api-reference/README.md Use this pattern to perform addition on values that conform to the CanAdd protocol. It ensures type safety by leveraging optype's protocol system. ```python import optype as op def double[T: op.CanAdd](value: T) -> T: """Double a value that supports addition.""" return op.do_add(value, value) ``` -------------------------------- ### OpType Type Conversion with Protocols Source: https://github.com/jorenham/optype/blob/master/_autodocs/README.md Shows type conversion using the op.CanInt protocol to convert objects to integers. ```python # Type conversion with protocols def maybe_to_int(obj: object) -> int | None: if isinstance(obj, op.CanInt): return op.do_int(obj) return None ```