簡體   English   中英

如何修復 mypy 錯誤,“Expression has type Any [misc]”,對於 int __pow__ int 的 python 類型提示?

[英]How to fix mypy error, "Expression has type Any [misc]", for python type hinting of int __pow__ int?

我有一個 python 函數,它使用帶有兩個 int 的 python __pow__ (**) 運算符,Mypy 告訴我表達式b ** e類型為“Any”,其中 b 和 e 的類型為“int”。 我試圖用int(b ** e)將表達式轉換為 int,但我仍然收到錯誤消息。 如何正確鍵入提示此表達式?

另外,如果表達式b ** e確實返回類型“Any”,您能解釋一下原因嗎?

錯誤:

temp.py:7: error: Expression has type "Any"  [misc]
        power: Callable[[int, int], int] = lambda b, e: b ** e
                                                        ^

臨時文件

from functools import reduce
from typing import Callable, Dict


def factorization_product(fact: Dict[int, int]) -> int:
    '''returns the product which has the prime factorization of fact'''
    power: Callable[[int, int], int] = lambda b, e: b ** e # error on expression "b ** e"
    product: Callable[[int, int], int] = lambda x, y: x * y
    return reduce(product, [power(b, e) for b, e in fact.items()], 1)

編輯:

我意識到我可以使用內置的 pow 和 operator.mul 而不是 lambda 的,但我仍然收到錯誤消息。

錯誤:

temp.py:8: error: Expression has type "Any"  [misc]
        return reduce(mul, [pow(b, e) for b, e in fact.items()], 1)
                            ^

修改后的temp.py

from functools import reduce
from operator import mul
from typing import Dict


def factorization_product(fact: Dict[int, int]) -> int:
    '''returns the product which has the prime factorization of fact'''
    return reduce(mul, [pow(b, e) for b, e in fact.items()], 1)

另外,如果表達式 b ** e 確實返回類型“Any”,您能解釋一下原因嗎?

檢查typeshed顯示僅在平方數字(類型為Literal[2] x的特殊情況下返回int 這是因為即使beint s, e也可能是負數,在這種情況下,結果是一個float 由於結果可以是floatint ,因此對於一般情況, typeshedAny一起使用。

我會說這是語言限制。 理想情況下,我們可以對x所有非負整數使用@overload ,但Literal僅支持特定值。

要在使用--disallow-any-expr同時解決這個問題,請使用typing.cast,如下所示:

power: Callable[[int, int], int] = lambda b, e: typing.cast(int, b ** e)

運行mypy --disallow-any-expr temp.py現在返回Success: no issues found in 1 source file mypy --disallow-any-expr temp.py Success: no issues found in 1 source file

但是在盲目添加cast ,請考慮我提出的場景,其中e為負,如果您對factorization_product的結果進行特定於int操作,則會導致類型檢查成功但運行時失敗。 您可能希望在此處添加驗證。 例如,沒有驗證:

factorial_sized_lst = [0] * factorization_product({1: 2, 3: -4})

盡管mypy報告類型檢查成功,但在運行時失敗, can't multiply sequence by non-int of type 'float'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM