TypeConstraint#

class overload_numpy.constraints.TypeConstraint#

Bases: object

ABC for constraining an argument type.

Warning

This class will be converted to a runtime-checkable Protocol when mypyc behaves nicely with runtime_checkable interpreted subclasses (see mypyc/mypyc#909).

Examples

It’s very easy to define a custom type constraint.

>>> from dataclasses import dataclass
>>> from overload_numpy.constraints import TypeConstraint
>>> @dataclass(frozen=True)
... class ThisOrThat(TypeConstraint):
...     this: type
...     that: type
...     def validate_type(self, arg_type: type, /) -> bool:
...         return arg_type is self.this or arg_type is self.that

Methods

validate_object(arg, /)

Validate an argument.

validate_type(arg_type, /)

Validate the argument type.

Methods Summary

validate_object(arg, /)

Validate an argument.

validate_type(arg_type, /)

Validate the argument type.

Methods Documentation

validate_object(arg: object, /) bool#

Validate an argument.

This is used in overload_numpy.mixin.NPArrayFuncOverloadMixin and subclasses like overload_numpy.mixin.NPArrayOverloadMixin to ensure that the input is of the correct set of types to work with the __array_function__ override.

Parameters:
argobject, positional-only

The argument that’s type must fit the type constraint.

Returns:
bool

Whether the type is valid.

Examples

The simplest built-in type constraint is overload_numpy.constraints.Invariant.

>>> from overload_numpy.constraints import Invariant
>>> constraint = Invariant(int)
>>> constraint.validate_type(int)  # exact type
True
>>> constraint.validate_type(bool)  # subclass
False
abstract validate_type(arg_type: type, /) bool#

Validate the argument type.

This is used in overload_numpy.mixin.NPArrayFuncOverloadMixin and subclasses like overload_numpy.mixin.NPArrayOverloadMixin to ensure that the input is of the correct set of types to work with the __array_function__ override.

Parameters:
arg_typetype, positional-only

The type of the argument that must fit the type constraint.

Returns:
bool

Whether the type is valid.

Examples

The simplest built-in type constraint is overload_numpy.constraints.Invariant.

>>> from overload_numpy.constraints import Invariant
>>> constraint = Invariant(int)
>>> constraint.validate_type(int)  # exact type
True
>>> constraint.validate_type(bool)  # subclass
False