TypeVar 绑定在 TypeVar 上的解决方法?

Joe*_*ley 13 python types type-hinting type-bounds

有没有办法用 Python 的类型提示来表达这个 Scala 代码?

trait List[A] {
  def ::[B >: A](x: B): List[B]
}
Run Code Online (Sandbox Code Playgroud)

我正在努力实现这种事情

class X: pass
class Y(X): pass

ys = MyList(Y(), Y())  # inferred as MyList[Y], I know how to do this
xs = ys.extended_by(X())  # inferred as MyList[X], I don't know how to do this
Run Code Online (Sandbox Code Playgroud)

请注意,类型MyList是用初始化的,它的类型extended_by可以是任何东西。有关更多详细信息,请参阅评论。

我试过的

from __future__ import annotations
from typing import TypeVar, Generic

B = TypeVar('B')
A = TypeVar('A', bound=B)


class MyList(Generic[A]):
    def __init__(*o: A):
        ...

    def extended_by(self, x: B) -> MyList[B]:
        ...
Run Code Online (Sandbox Code Playgroud)

但我明白了(上面在 main.py 中)

main.py:5:错误:类型变量“main.B”未绑定
main.py:5:注意:(提示:使用“Generic[B]”或“Protocol[B]”基类在内部绑定“B”一个类)
main.py:5:注意:(提示:在函数签名中使用“B”来绑定函数内部的“B”)

Afaict,不允许绑定到TypeVar. 在这种情况下有解决方法吗?

Cyr*_*eux -2

from __future__ import annotations\n\nfrom typing import (\n    TYPE_CHECKING,\n    Generic,\n    TypeVar,\n)\n\nB = TypeVar(\'B\')\nA = TypeVar(\'A\')\n\n\nclass MyList(Generic[A]):\n    def __init__(*o: A):\n        ...\n\n    def extended_by(self, x: B) -> MyList[B]:\n        ...\n\n\nclass Y:\n    ...\n\n\nclass X:\n    ...\n\n\nys = MyList(Y(), Y())\nxs = ys.extended_by(X())\nif TYPE_CHECKING:\n    reveal_locals()\n
Run Code Online (Sandbox Code Playgroud)\n

这会产生:

\n
test.py:32: note: Revealed local types are:\ntest.py:32: note:     xs: test.MyList[test.X*]\ntest.py:32: note:     ys: test.MyList[test.Y*]\n
Run Code Online (Sandbox Code Playgroud)\n

A我不明白\xe2\x80\x99t和 之间的联系B。您能否举一个实例类的例子YX以便我可以更新我的答案?

\n