我似乎无法使泛型类型正常工作。我在继承Deque。 Deque的每个项目都是SomeNamedTuple的实例。
T(n) = 2 T(n/2) + c for all n > 1, where c is some constant. And
T(n) = 1 when n = 1
So T(n) = 2 T(n/2) + c, now start substituting T(n/2) and move one
=> T(n) = 2 [ 2 T(n/4) + c ] + c
=> T(n) = 2^2T(n/4) + 2c
Now substitute t(n/4) as well
=> T(n) = 2^2[2 T(n/8) + c] + 2c
=> T(n) = 2^3T(n/8) + 3c
Now assume that if we keep dividing like this, at some point we will reach 1 i.e., when n/2^k = 1, then T(1) = 1
=> T(n) = 2^kT(n/2^k) + kc
Now since we know that n/2^k = 1
=> k = log n (I am representing log as base 2)
Therefore substitute k value in above T(n) equation to get
=> T(n) = 2^(log n) T(1) + c log n
=> T(n) = n T(1) + c log n (Check log rule on how we got n for first coefficient)
=> T(n) = n + c log n (since T(1) = 1)
from typing import NamedTuple, Deque, TypeVar
class SomeNamedTuple(NamedTuple):
field1: int
field2: str
T = TypeVar("T", bound=NamedTuple)
class SomeDeque(Deque[T]):
def some_method(self) -> None:
if self:
print(self[0]._fields)
mydeque = SomeDeque[SomeNamedTuple]()
我在mypy / applytype.py中进行了一些调试,生成了错误:
$ mypy --strict foo.py
foo.py:14: error: Value of type variable "T" of "SomeDeque" cannot be "SomeNamedTuple"
看起来它认为类型是元组(不是NamedTuple):
upper_bound = callable.variables[i].upper_bound
if not mypy.subtypes.is_subtype(type, upper_bound):
if skip_unsatisfied:
types[i] = None
else:
print(f'type = {type}')
print(f'upper_bound = {upper_bound}')
msg.incompatible_typevar_value(callable, type, callable.variables[i].name, context)
我在做什么错了?