亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我可以使用來自另一個函數的輸入信息作為 Python 中的返回類型嗎?

我可以使用來自另一個函數的輸入信息作為 Python 中的返回類型嗎?

陪伴而非守候 2022-07-12 17:49:24
在以下示例中,如何正確注釋sum_two函數的返回類型?from typing import Any, TypeVarT = TypeVar('T')S = TypeVar('S')def sum_two(first: T, second: S):    return first + second假設__add__運算符為將傳遞給此函數的所有可能參數正確注釋,是否有某種方法可以將返回類型表示為調用類型和__add__對象的返回類型?TS我想避免使用打字的overload裝飾器來識別所有可能的情況,因為可能有幾十種情況。
查看完整描述

1 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

理論上,您可以通過制作一個通用協議來完成他的一部分first,它可以讓您“捕獲” __add__. 例如:


# If you are using Python 3.7 or earlier, you'll need to pip-install

# the typing_extensions module and import Protocol from there.

from typing import TypeVar, Protocol, Generic


TOther = TypeVar('TOther', contravariant=True)

TSum = TypeVar('TSum', covariant=True)


class SupportsAdd(Protocol, Generic[TOther, TSum]):

    def __add__(self, other: TOther) -> TSum: ...


然后,您可以執行以下操作:


S = TypeVar('S')

R = TypeVar('R')


# Due to how we defined the protocol, R will correspond to the

# return type of `__add__`.

def sum_two(first: SupportsAdd[S, R], second: S) -> R:

    return first + second


# Type checks

reveal_type(sum_two("foo", "bar"))  # Revealed type is str

reveal_type(sum_two(1, 2))          # Revealed type is int

reveal_type(sum_two(1.0, 2))        # Revealed type is float


# Does not type check, since float's __radd__ is ignored

sum_two(1, 2.0)


class Custom:

    def __add__(self, x: int) -> int:

        return x


# Type checks

reveal_type(sum_two(Custom(), 3))  # Revealed type is int


# Does not type check

reveal_type(sum_two(Custom(), "bad"))

但是,這種方法確實有一些限制:

  1. 它不處理__add__在“第一”中沒有匹配但__radd__在“第二”中有匹配的情況。

  2. 如果你修改自定義,你可能會得到一些奇怪的結果,所以這__add__是一個重載。我認為至少 mypy 目前有一個錯誤,它不知道如何正確處理涉及子類型和重載的復雜情況。


查看完整回答
反對 回復 2022-07-12
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號