【发布时间】:2022-10-24 03:30:54
【问题描述】:
我有一个排序的链表
class SortedLinkedList:
# ...
def insert(self, value: int):
# ...
if node.value > value:
self.add_before(node, value)
# ...
我想通过实现__gt__() 魔术方法来概括Node 只能从ints 到重载> 运算符的任何对象的值类型。
在其他语言中,我可以通过使用Interface 来实现这一点,但 Python 显然没有类似的东西。我已经看到了通过使用抽象类来伪造接口的建议,例如
class Sortable(ABC):
@abstractmethod
def __gt__(self, other) -> bool:
pass
class SortedLinkedList:
# ...
def insert(self, value: Sortable, node: Node):
# ...
问题是这种方法需要扩展和使用来自Sortable 的子类,这意味着不能使用已经具有> 功能(如整数)的类型
linkedlist.insert(5) # Pylance red squiggles
Argument of type "Literal[5]" cannot be assigned to
parameter "value" of type "Sortable" in function "insert"
"Literal[5]" is incompatible with "Sortable" Pylance(reportGeneralTypeIssues)
我知道,鉴于 Python 的动态鸭子类型和隐式风格,接口在运行前不是必需的。我不是粉丝,我选择使用typing 和Pylance 等可用工具来实现严格类型化的开发人员体验。
我也不希望使用像.hasattr(value, '__gt__') 这样的运行时检查。我希望它在类型系统/语言服务器/IDE 级别上注册,因为表达性、可读性和 IDE 智能感知是严格类型的主要好处。
有什么办法可以做到这一点?
【问题讨论】:
标签: python python-typing pylance