Python:为魔术方法“__str__”和“__repr__”重载 return 类型
Python: overloading the return type for magic methods `__str__` and `__repr__`
我有一个自定义枚举 class,它在调用 __str__
或 __repr__
时只能 return 一组特定的字符串文字。鉴于这些序列化字符串文字有时用作其他函数的输入(并且这些输入类型正确,即仅限于正确的字符串集),我想要 return 类型的 __str__
和__repr__
比 str
.
更精确
考虑以下几点:
from typing import Literal
class A:
def __repr__(self) -> Literal["world"]:
result : Literal["world"] = "world"
return result
test_val : Literal["world"] = repr(A())
print(test_val)
以上应该有效,因为类型注释是连贯的,但是对于 mypy,我得到:
playground.py:8: error: Incompatible types in assignment (expression has type "str", variable has type "Literal['world']")
对于我分配test_val
的行。
我怀疑这可能是由于某种关于如何定义 dunder 方法类型的全局机制造成的; __repr__
总是 return 一个字符串。但是考虑到我可以为 __getitem__
选择我的 return 类型就好了,我认为其他方法可能是可行的。
有没有办法强制重载return类型的__str__
/__repr__
只要co/contra-variance,Liskov等等, 受到尊重 ?
您的方法输入正确,但您混淆了 repr
和 __repr__
。 A().__repr__()
returns 一个 Literal["world"]
但 repr
,带有签名
def repr(x: object) -> str: ...
总是returns一个str
我有一个自定义枚举 class,它在调用 __str__
或 __repr__
时只能 return 一组特定的字符串文字。鉴于这些序列化字符串文字有时用作其他函数的输入(并且这些输入类型正确,即仅限于正确的字符串集),我想要 return 类型的 __str__
和__repr__
比 str
.
考虑以下几点:
from typing import Literal
class A:
def __repr__(self) -> Literal["world"]:
result : Literal["world"] = "world"
return result
test_val : Literal["world"] = repr(A())
print(test_val)
以上应该有效,因为类型注释是连贯的,但是对于 mypy,我得到:
playground.py:8: error: Incompatible types in assignment (expression has type "str", variable has type "Literal['world']")
对于我分配test_val
的行。
我怀疑这可能是由于某种关于如何定义 dunder 方法类型的全局机制造成的; __repr__
总是 return 一个字符串。但是考虑到我可以为 __getitem__
选择我的 return 类型就好了,我认为其他方法可能是可行的。
有没有办法强制重载return类型的__str__
/__repr__
只要co/contra-variance,Liskov等等, 受到尊重 ?
您的方法输入正确,但您混淆了 repr
和 __repr__
。 A().__repr__()
returns 一个 Literal["world"]
但 repr
,带有签名
def repr(x: object) -> str: ...
总是returns一个str