子类字符串并让 MyPy 开心

Subclass string and keep MyPy happy

如何使这段代码 运行 成功并通过 mypy 检查?

from datetime import datetime

class TimeStamp(str):
    """ID with a short form and a long form."""
    
    def __new__(cls, datetime) -> TimeStamp:
        short = str(datetime.timestamp())
        long = datetime.strftime("%Y-%m-%d %H:%M:%S")
        obj = str.__new__(cls, short)
        obj.short = short
        obj.long = long
        return obj

now = TimeStamp(datetime.now())
print(now)
print(now.long)

当前 mypy untitled1.py 导致以下错误:

untitled1.py:10: error: "TimeStamp" has no attribute "short"
untitled1.py:11: error: "TimeStamp" has no attribute "long"
untitled1.py:16: error: "TimeStamp" has no attribute "long"
Found 3 errors in 1 file (checked 1 source file)

如果我在 __new__ 中省略 return 类型,MyPy 会非常满意。但是我必须为对象属性做类型注释。所以解决方案如下所示:

from datetime import datetime

class TimeStamp(str):
    """ID with a short form and a long form."""
    
    short: str
    long: str
    
    def __new__(cls, datetime):
        short = str(datetime.timestamp())
        long = datetime.strftime("%Y-%m-%d %H:%M:%S")
        obj = str.__new__(cls, short)
        obj.short = short
        obj.long = long
        return obj

now = TimeStamp(datetime.now())
print(now)
print(now.long)

这通过了 MyPy 检查并且可以是 运行。