Building blocks for precise & flexible Python type hints
Project description
optype
One protocol, one method.
Building blocks for precise & flexible type hints.
Installation
Optype is available as optype
on PyPI:
pip install optype
Overview
The API of optype
is flat; a single import optype
is all you need.
There are four flavors of things that live within optype
,
optype.Can{}
types describe what can be done with it. For instance, anyCanAbs[T]
type can be used as argument to theabs()
builtin function with return typeT
. MostCan{}
implement a single special method, whose name directly matched that of the type.CanAbs
implements__abs__
,CanAdd
implements__add__
, etc.optype.Has{}
is the analogue ofCan{}
, but for special attributes.HasName
has the__name__: str
attribute,HasDict
has a__dict__
, etc.optype.Does{}
describe the type of operators. SoDoesAbs
is the type of theabs({})
builtin function, andDoesPos
the type of the+{}
prefix operator.optype.do_{}
are the correctly-typed implementations ofDoes{}
. For eachdo_{}
there is aDoes{}
, and vice-versa. Sodo_abs: DoesAbs
is the typed alias ofabs({})
, anddo_pos: DoesPos
is a typed version ofoperator.pos
. Theoptype.do_
operators are more complete thanoperators
, has runtime-accessible type annotations, and uses a fully predictable naming scheme.
Reference
All typing protocols here live in the root optype
namespace.
They are runtime-checkable so that you can do e.g.
isinstance('snail', optype.CanAdd)
, in case you want to check whether
snail
implements __add__
.
[!NOTE] It is bad practice to use a
typing.Protocol
as base class for your implementation. Because of@typing.runtime_checkable
, you can useisinstance
either way.
Unlikecollections.abc
, optype
's protocols aren't abstract base classes,
i.e. they don't extend abc.ABC
, only typing.Protocol
.
This allows the optype
protocols to be used as building blocks for .pyi
type stubs.
Type conversion
The return type of these special methods is invariant. Python will raise an
error if some other (sub)type is returned.
This is why these optype
interfaces don't accept generic type arguments.
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
bool(_) |
do_bool |
DoesBool |
__bool__ |
CanBool |
int(_) |
do_int |
DoesInt |
__int__ |
CanInt |
float(_) |
do_float |
DoesFloat |
__float__ |
CanFloat |
complex(_) |
do_complex |
DoesComplex |
__complex__ |
CanComplex |
bytes(_) |
do_bytes |
DoesBytes |
__bytes__ |
CanBytes |
str(_) |
do_str |
DoesStr |
__str__ |
CanStr |
These formatting methods are allowed to return instances that are a subtype
of the str
builtin. The same holds for the __format__
argument.
So if you're a 10x developer that wants to hack Python's f-strings, but only
if your type hints are spot-on; optype
is you friend.
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
repr(_) |
do_repr |
DoesRepr |
__repr__ |
CanRepr[Y: str] |
format(_, x) |
do_format(_, x) |
DoesFormat |
__format__ |
CanFormat[X: str, Y: str] |
"Rich comparison" operators
These special methods generally a bool
. However, instances of any type can
be returned.
operator | operand | ||||
---|---|---|---|---|---|
expression | reflected | function | type | method | type |
_ < x |
x > _ |
do_lt |
DoesLt |
__lt__ |
CanLt[X, Y] |
_ <= x |
x >= _ |
do_le |
DoesLe |
__le__ |
CanLe[X, Y] |
_ == x |
x == _ |
do_eq |
DoesEq |
__eq__ |
CanEq[X, Y] |
_ != x |
x != _ |
do_ne |
DoesNe |
__ne__ |
CanNe[X, Y] |
_ > x |
x < _ |
do_gt |
DoesGt |
__gt__ |
CanGt[X, Y] |
_ >= x |
x <= _ |
do_ge |
DoesGe |
__ge__ |
CanGe[X, Y] |
Callable objects
Unlike operator
, optype
provides the operator for callable objects:
optype.do_call(f, *args. **kwargs)
.
CanCall
is similar to collections.abc.Callable
, but is runtime-checkable,
and doesn't use esoteric hacks.
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
_(*args, **kwargs) |
do_call |
DoesCall |
__call__ |
CanCall[**Xs, Y] |
Numeric operations
For describing things that act like numbers. See the Python docs for more info.
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
_ + x |
do_add |
DoesAdd |
__add__ |
CanAdd[X, Y] |
_ - x |
do_sub |
DoesSub |
__sub__ |
CanSub[X, Y] |
_ * x |
do_mul |
DoesMul |
__mul__ |
CanMul[X, Y] |
_ @ x |
do_matmul |
DoesMatmul |
__matmul__ |
CanMatmul[X, Y] |
_ / x |
do_truediv |
DoesTruediv |
__truediv__ |
CanTruediv[X, Y] |
_ // x |
do_floordiv |
DoesFloordiv |
__floordiv__ |
CanFloordiv[X, Y] |
_ % x |
do_mod |
DoesMod |
__mod__ |
CanMod[X, Y] |
divmod(_, x) |
do_divmod |
DoesDivmod |
__divmod__ |
CanDivmod[X, Y] |
_ ** x pow(_, x)
|
do_pow |
DoesPow |
__pow__ |
CanPow2[X, Y2] CanPow[X, None, Y2, Any]
|
pow(_, x, m) |
do_pow |
DoesPow |
__pow__ |
CanPow3[X, M, Y3] CanPow[X, M, Any, Y3]
|
_ << x |
do_lshift |
DoesLshift |
__lshift__ |
CanLshift[X, Y] |
_ >> x |
do_rshift |
DoesRshift |
__rshift__ |
CanRshift[X, Y] |
_ & x |
do_and |
DoesAnd |
__and__ |
CanAnd[X, Y] |
_ ^ x |
do_xor |
DoesXor |
__xor__ |
CanXor[X, Y] |
_ | x |
do_or |
DoesOr |
__or__ |
CanOr[X, Y] |
Note that because pow()
can take an optional third argument, optype
provides separate interfaces for pow()
with two and three arguments.
Additionally, there is the overloaded intersection type
CanPow[X, M, Y2, Y3] =: CanPow2[X, Y2] & CanPow3[X, M, Y3]
, as interface
for types that can take an optional third argument.
For the binary infix operators above, optype
additionally provides
interfaces with reflected (swapped) operands:
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
x + _ |
do_radd |
DoesRAdd |
__radd__ |
CanRAdd[X, Y] |
x - _ |
do_rsub |
DoesRSub |
__rsub__ |
CanRSub[X, Y] |
x * _ |
do_rmul |
DoesRMul |
__rmul__ |
CanRMul[X, Y] |
x @ _ |
do_rmatmul |
DoesRMatmul |
__rmatmul__ |
CanRMatmul[X, Y] |
x / _ |
do_rtruediv |
DoesRTruediv |
__rtruediv__ |
CanRTruediv[X, Y] |
x // _ |
do_rfloordiv |
DoesRFloordiv |
__rfloordiv__ |
CanRFloordiv[X, Y] |
x % _ |
do_rmod |
DoesRMod |
__rmod__ |
CanRMod[X, Y] |
divmod(x, _) |
do_rdivmod |
DoesRDivmod |
__rdivmod__ |
CanRDivmod[X, Y] |
x ** _ pow(x, _)
|
do_rpow |
DoesRPow |
__rpow__ |
CanRPow[X, Y] |
x << _ |
do_rlshift |
DoesRLshift |
__rlshift__ |
CanRLshift[X, Y] |
x >> _ |
do_rrshift |
DoesRRshift |
__rrshift__ |
CanRRshift[X, Y] |
x & _ |
do_rand |
DoesRAnd |
__rand__ |
CanRAnd[X, Y] |
x ^ _ |
do_rxor |
DoesRXor |
__rxor__ |
CanRXor[X, Y] |
x | _ |
do_ror |
DoesROr |
__ror__ |
CanROr[X, Y] |
Note that CanRPow
corresponds to CanPow2
; the 3-parameter "modulo" pow
does not reflect in Python.
Similarly, the augmented assignment operators are described by the following
optype
interfaces:
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
_ += x |
do_iadd |
DoesIAdd |
__iadd__ |
CanIAdd[X, Y] |
_ -= x |
do_isub |
DoesISub |
__isub__ |
CanISub[X, Y] |
_ *= x |
do_imul |
DoesIMul |
__imul__ |
CanIMul[X, Y] |
_ @= x |
do_imatmul |
DoesIMatmul |
__imatmul__ |
CanIMatmul[X, Y] |
_ /= x |
do_itruediv |
DoesITruediv |
__itruediv__ |
CanITruediv[X, Y] |
_ //= x |
do_ifloordiv |
DoesIFloordiv |
__ifloordiv__ |
CanIFloordiv[X, Y] |
_ %= x |
do_imod |
DoesIMod |
__imod__ |
CanIMod[X, Y] |
_ **= x |
do_ipow |
DoesIPow |
__ipow__ |
CanIPow[X, Y] |
_ <<= x |
do_ilshift |
DoesILshift |
__ilshift__ |
CanILshift[X, Y] |
_ >>= x |
do_irshift |
DoesIRshift |
__irshift__ |
CanIRshift[X, Y] |
_ &= x |
do_iand |
DoesIAnd |
__iand__ |
CanIAnd[X, Y] |
_ ^= x |
do_ixor |
DoesIXor |
__ixor__ |
CanIXor[X, Y] |
_ |= x |
do_ior |
DoesIOr |
__ior__ |
CanIOr[X, Y] |
Additionally, there are the unary arithmetic operators:
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
+_ |
do_pos |
DoesPos |
__pos__ |
CanPos[Y] |
-_ |
do_neg |
DoesNeg |
__neg__ |
CanNeg[Y] |
~_ |
do_invert |
DoesInvert |
__invert__ |
CanInvert[Y] |
abs(_) |
do_abs |
DoesAbs |
__abs__ |
CanAbs[Y] |
The round()
built-in function takes an optional second argument.
From a typing perspective, round()
has two overloads, one with 1 parameter,
and one with two.
For both overloads, optype
provides separate operand interfaces:
CanRound1[Y]
and CanRound2[N, Y]
.
Additionally, optype
also provides their (overloaded) intersection type:
CanRound[N, Y1, Y2] = CanRound1[Y1] & CanRound2[N, Y2]
.
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
round(_) |
do_round |
DoesRound |
__round__/1 |
CanRound1[Y1] CanRound[None, Y1, Any] |
round(_, n) |
do_round |
DoesRound |
__round__/2 |
CanRound2[N, Y2] CanRound[N, Any, Y2] |
round(_, n=None) |
do_round(_, n=None) |
DoesRound |
__round__ |
CanRound[N, Y1, Y2] |
For example, type-checkers will mark the following code as valid (tested with pyright in strict mode):
x: float = 3.14
x1: CanRound1[int] = x
x2: CanRound2[int, float] = x
x3: CanRound[int, int, float] = x
Furthermore, there are the alternative rounding functions from the
math
standard library:
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
math.trunc(_) |
do_trunc |
DoesTrunc |
__trunc__ |
CanTrunc[Y] |
math.floor(_) |
do_floor |
DoesFloor |
__floor__ |
CanFloor[Y] |
math.ceil(_) |
do_ceil |
DoesCeil |
__ceil__ |
CanCeil[Y] |
Note that the type parameter Y
has no upper type bound, because technically
these methods can return any type. However, in practise, it is very common to
have them return an int
.
Async objects
The optype
variant of collections.abc.Awaitable[V]
. The only difference
is that optype.CanAwait[V]
is a pure interface, whereas Awaitable
is
also an abstract base class.
operator | operand | |
---|---|---|
expression | method | type |
await _ |
__await__ |
CanAwait[V] |
Iteration
The operand x
of iter(_)
is within Python known as an iterable, which is
what collections.abc.Iterable[K]
is often used for (e.g. as base class, or
for instance checking).
The optype
analogue is CanIter[Ks]
, which as the name suggests,
also implements __iter__
. But unlike Iterable[K]
, its type parameter Ks
binds to the return type of iter(_)
. This makes it possible to annotate the
specific type of the iterable that iter(_)
returns. Iterable[K]
is only
able to annotate the type of the iterated value. To see why that isn't
possible, see python/typing#548.
The collections.abc.Iterator[K]
is even more awkward; it is a subtype of
Iterable[K]
. For those familiar with collections.abc
this might come as a
surprise, but an iterator only needs to implement __next__
, __iter__
isn't
needed. This means that the Iterator[K]
is unnecessarily restrictive.
Apart from that being theoretically "ugly", it has significant performance
implications, because the time-complexity of isinstance
on a
typing.Protocol
is $O(n)$, with the $n$ referring to the amount of members.
So even if the overhead of the inheritance and the abc.ABC
usage is ignored,
collections.abc.Iterator
is twice as slow as it needs to be.
That's one of the (many) reasons that optype.CanNext[V]
and
optype.CanNext[V]
are the better alternatives to Iterable
and Iterator
from the abracadabra collections. This is how they are defined:
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
next(_) |
do_next |
DoesNext |
__next__ |
CanNext[V] |
iter(_) |
do_iter |
DoesIter |
__iter__ |
CanIter[Vs: CanNext] |
Async Iteration
Yes, you guessed it right; the abracadabra collections made the exact same mistakes for the async iterablors (or was it "iteramblers"...?).
But fret not; the optype
alternatives are right here:
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
anext(_) |
do_anext |
DoesANext |
__anext__ |
CanANext[V] |
aiter(_) |
do_aiter |
DoesAIter |
__aiter__ |
CanANext[Vs: CanAnext] |
But wait, shouldn't V
be a CanAwait
? Well, only if you don't want to get
fired...
Technically speaking, __anext__
can return any type, and anext
will pass
it along without nagging (instance checks are slow, now stop bothering that
liberal). For details, see the discussion at python/typeshed#7491.
Just because something is legal, doesn't mean it's a good idea (don't eat the
yellow snow).
Containers
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
len(_) |
__len__ |
CanLen |
||
_.__length_hint__()
(docs)
|
__length_hint__ |
CanLengthHint |
||
_[k] |
do_getitem |
DoesGetitem |
__getitem__ |
CanGetitem[K, V] |
_.__missing__()
(docs)
|
__missing__ |
CanMissing[K, V] |
||
_[k] = v |
do_setitem |
DoesSetitem |
__setitem__ |
CanSetitem[K, V] |
del _[k] |
do_delitem |
DoesDelitem |
__delitem__ |
CanDelitem[K] |
k in _ |
do_contains |
DoesContains |
__contains__ |
CanContains[K] |
reversed(_) |
__reversed__ |
CanReversed[Y] |
Because CanMissing[K, M]
generally doesn't show itself without
CanGetitem[K, V]
there to hold its hand, optype
conveniently stitched them
together as optype.CanGetMissing[K, V, M]
.
Additionally, optype
provides protocols for types with (custom) hash or
index methods:
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
hash(_) |
do_hash |
DoesHash |
__hash__ |
CanHash[V] |
_.__index__()
(docs)
|
do_index |
DoesIndex |
__index__ |
CanIndex[V] |
Attribute access
operator | operand | |||
---|---|---|---|---|
expression | function | type | method | type |
v = _.k orv = getattr(_, k)
|
do_getattr |
DoesGetattr |
__getattr__ |
CanGetattr[K: str, V] |
_.k = v orsetattr(_, k, v)
|
do_setattr |
DoesSetattr |
__setattr__ |
CanSetattr[K: str, V] |
del _.k ordelattr(_, k)
|
do_delattr |
DoesDelattr |
__delattr__ |
CanDelattr[K: str] |
dir(_) |
do_dir |
DoesDir |
__dir__ |
CanDir[Vs: CanIter] |
Descriptors
Interfaces for descriptors.
operator | operand | |
---|---|---|
expression | method | type |
class T: d = _ |
__set_name__ |
CanSetName[T] |
u = T.d v = T().d
|
__get__ |
CanGet[T: object, U, V] |
T().k = v |
__set__ |
CanSet[T, V] |
del T().k |
__delete__ |
CanDelete[T] |
Context managers
Support for the with
statement.
operator | operand | |
---|---|---|
expression | method(s) | type |
with _ as v |
__enter__ , __exit__ |
CanWith[V, R] |
__enter__ |
CanEnter[V] |
|
__exit__ |
CanExit[R] |
For the async with
statement the interfaces look very similar:
operator | operand | |
---|---|---|
expression | method(s) | type |
async with _ as v |
__aenter__ , __aexit__ |
CanAsyncWith[V, R] |
__aenter__ |
CanAEnter[V] |
|
__aexit__ |
CanAExit[R] |
Buffer types
Interfaces for emulating buffer types using the buffer protocol.
operator | operand | |
---|---|---|
expression | method | type |
v = memoryview(_) |
__buffer__ |
CanBuffer[B: int] |
del v |
__release_buffer__ |
CanReleaseBuffer |
Future plans
- Support for Python versions before 3.12.
- More standard library protocols, e.g.
copy
,dataclasses
,pickle
. - Typed mixins for DRY implementation of operator, e.g. for comparison ops
GeFromLt
,GtFromLe
, etc as a typed alternative forfunctools.total_ordering
. Similarly for numeric types, with e.g.__add__
and__neg__
a mixin could generate__pos__
and__sub__
. - Dependency-free third-party type support, e.g. protocols for
numpy
's array interface.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file optype-0.2.1.tar.gz
.
File metadata
- Download URL: optype-0.2.1.tar.gz
- Upload date:
- Size: 25.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.2 CPython/3.11.5 Linux/6.6.10-76060610-generic
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b8dd37015200434a48f6989afceefb0ac41d1a8ea85c2bc1e70c2af473867562 |
|
MD5 | b08ea32ab912cb4361bd4cb4c6c5d88a |
|
BLAKE2b-256 | 39fe4ab90420fd29483e97b207f4856409e03adef5fb0a6a665c3d305c0d6aa7 |
File details
Details for the file optype-0.2.1-py3-none-any.whl
.
File metadata
- Download URL: optype-0.2.1-py3-none-any.whl
- Upload date:
- Size: 18.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.2 CPython/3.11.5 Linux/6.6.10-76060610-generic
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4c0ac282db4970e07c853339d831a86bb0b14f074283ac6f06a1b9f8cca5ca10 |
|
MD5 | bbd819cd31ae9402dca93181bbaa6f00 |
|
BLAKE2b-256 | 2b731541f89fc010a30a27bf1e395ebf2dc70d01ceb2d729b04c7b9bf613a8fd |