Mypy:注释函数,其中返回类型取决于参数的类型

zef*_*ciu 2 python type-hinting mypy python-typing

我有一个代表标准化内存量的类。

class MemoryUnit(enum.Enum):
    """Units of memory."""

    GB = 'GB'
    TB = 'TB'
    PB = 'PB'
Run Code Online (Sandbox Code Playgroud)
class Memory(BaseModel):
    """Normalized amount of memory."""

    amount: int
    unit: MemoryUnit
Run Code Online (Sandbox Code Playgroud)

现在我想为这个班级实现基本算术。加法、减法和乘法很容易注释:

def __add__(self, other: Memory) -> Memory: ...
def __sub__(self, other: Memory) -> Memory: ...
def __mul__(self, other: int) -> Memory: ...
Run Code Online (Sandbox Code Playgroud)

不过,我对分裂有疑问。我看到除法的两个用例:

  • 除以MemoryMemory得到 a float(两个存储量之间的比率是多少)。
  • 除以Memoryint得到(如果均匀除以Memory的数量是多少)Memoryn

mypy 有没有办法用这个特定的签名来注释函数?

Ale*_*ood 6

typing.overload允许您注册一个函数的多个不同签名。用 \xe2\x80\x94 修饰的函数@overload在运行时会被忽略,它们只是为了类型检查器的好处 \xe2\x80\x94 所以你可以将这些函数的主体留空。通常,您只需放置文字省略号...、文档字符串或pass在这些函数的正文中此外,您还需要确保该函数至少有一种具体实现可供在运行时使用。

\n
from typing import overload, Union\n\nclass Memory(BaseModel):\n    """Normalized amount of memory."""\n\n    amount: int\n    unit: MemoryUnit\n\n    def __add__(self, other: Memory) -> Memory: ...\n    def __sub__(self, other: Memory) -> Memory: ...\n    def __mul__(self, other: int) -> Memory: ...\n\n    @overload\n    def __div__(self, other: Memory) -> float:\n        """Signature of `Memory.__div__` if an instance of `Memory`\n        is divided by another instance of `Memory`\n        """\n\n    @overload\n    def __div__(self, other: int) -> Memory:\n        """Signature of `Memory.__div__` if an instance of `Memory`\n        is divided by an `int`\n        """\n\n    def __div__(self, other: Union[int, Memory]) -> Union[Memory, float]:\n        """[Your actual runtime implementation goes here]"""\n
Run Code Online (Sandbox Code Playgroud)\n