Python 中不可变对象的类型是什么(对于 mypy)
What is the type of immutable object in Python (for mypy)
我总是在我的 Python 程序中使用 mypy
。
不可变对象的类型(来自 typing
)是什么,可以用作字典键的对象?
回到上下文,我想写一个 class 继承自字典,我有以下代码
class SliceableDict(dict):
def __getitem__(self, attr:Any) -> Any:
return super().__getitem__(attr)
在那种情况下,类型提示毫无用处,不是吗?
谢谢
typing.Hashable
指的是可以作为 dict
中的有效键或 set
中的值的任何类型。
它不要求真正的不变性(任何对象都可以define __hash__
),但一般来说,可散列的东西应该是"treated as immutable"的东西,因为如果它们在插入 set
或作为 dict
键插入后发生变异,它会破坏事物。
dict
的键是hashable (see the first sentence of the docs on dict
), and the hashable type is typing.Hashable
, an alias for collections.abc.Hashable
。
我总是在我的 Python 程序中使用 mypy
。
不可变对象的类型(来自 typing
)是什么,可以用作字典键的对象?
回到上下文,我想写一个 class 继承自字典,我有以下代码
class SliceableDict(dict):
def __getitem__(self, attr:Any) -> Any:
return super().__getitem__(attr)
在那种情况下,类型提示毫无用处,不是吗?
谢谢
typing.Hashable
指的是可以作为 dict
中的有效键或 set
中的值的任何类型。
它不要求真正的不变性(任何对象都可以define __hash__
),但一般来说,可散列的东西应该是"treated as immutable"的东西,因为如果它们在插入 set
或作为 dict
键插入后发生变异,它会破坏事物。
dict
的键是hashable (see the first sentence of the docs on dict
), and the hashable type is typing.Hashable
, an alias for collections.abc.Hashable
。