in python 3.5 code below, want use less operator (<
) compare 2 generic values. how can declare constraint on t support __lt__
?
from typing import * import operator t = typevar('t') class mylist(generic[t]): class node: def __init__(self, k:t) -> none: self.key = k self.next = none # type: optional[mylist.node] def __init__(self) -> none: self.root = none # type: optional[mylist.node] def this_works(self, val:t) -> bool: return self.root.key == val def not_works(self, val:t) -> bool: return operator.lt(self.root.key, val)
i'm using mypy type check , it's failing on not_works
message:
$ mypy test.py test.py: note: in member "not_works" of class "mylist": test.py:20: error: unsupported left operand type < ("t")
other languages support constraints on t.
in c#: class mylist<t> t:icomparable<t>
in java: class mylist<t extends comparable<? super t>>
well looking @ same issue , turns out can achieve goal passing parameter bound
typevar
, described in pep484:
a type variable may specify upper bound using
bound=<type>
. means actual type substituted (explicitly or implicitly) type variable must subtype of boundary type. common example definition of comparable type works enough catch common errors:
sample code mentioned pep:
from typing import typevar class comparable(metaclass=abcmeta): @abstractmethod def __lt__(self, other: any) -> bool: ... ... # __gt__ etc. ct = typevar('ct', bound=comparable) def min(x: ct, y: ct) -> ct: if x < y: return x else: return y min(1, 2) # ok, return type int min('x', 'y') # ok, return type str
Comments
Post a Comment