gpt4 book ai didi

python - Into 和 From 接口(interface) : struggling with typing. 类型的协方差

转载 作者:行者123 更新时间:2023-12-03 17:38:35 24 4
gpt4 key购买 nike

我正在尝试为类型之间的转换实现一个接口(interface),但自 typing.Type 以来我一直在努力使其保持一致。是协变的

U = TypeVar('U')


class Into(Protocol[U]):
@abstractmethod
def into(self, t: Type[U]) -> U:
pass

docs举一个有关键区别的类似例子
class User: ...
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...

def make_new_user(user_class: Type[User]) -> User:
return user_class()

他们说类型检查器应该检查 User 的所有子类应该实现一个具有有效签名的构造函数,以便像这样实例化。我的用例不同,因为我可能没有构建新类型,只是返回一个预先存在的类型。说我同意
class X: pass

class Wrapper:
def __init__(self, x: X):
self._x = x

def into(self, t: Type[X]) -> X:
return self._x

一切正常,直到有人继承 X
w = Wrapper(X())
...
class XX(X): pass
x: XX = w.into(XX)

RHS 很好,mypy cos Type是协变的,但显然 API 已损坏,因为 X不是 XX .如果 Type不是协变的,这不会是一个问题:RHS 直到 Wrapper 才会进行类型检查已更新以支持 XX .

我的问题是:鉴于 Type 的协方差,是否有某种方法可以实现这一点(或类似的东西)? ?

上下文

我想使用它来将一个类型转换为多种其他类型,明确指定所需的类型,而不仅仅是 into_X , into_Y等等。我希望用 TypeVar 来做到这一点或 overload .我也有困难 there .

这是受 rust 的 Into 启发的。 , 其中 t: Type[U]是类型参数而不是函数参数。

最佳答案

eval解决了这个问题。

class Wrapper:
def __init__(self, x: X):
self._x = x

def into(self, t: Type[X]) -> X:
return eval(f'{t}({self._x})')

关于python - Into 和 From 接口(interface) : struggling with typing. 类型的协方差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58354671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com