簡體   English   中英

mypy 數值類型的返回值類型不兼容

[英]mypy Incompatible return value type for numeric types

考慮這個例子

from typing import TypeVar

Even = TypeVar("Even",bound=int)
Odd  = TypeVar("Odd",bound=int)


def make_even(n:int) -> Even:
    return n*2
    
def make_odd(n:int) -> Odd:
    return n*2+1

def make_both(n:int) -> tuple[Even,Odd]:
    return make_even(n), make_odd(n)

help(make_both)

它的輸出很好,就像我想要的一樣

Help on function make_both in module __main__:

make_both(n: int) -> tuple[~Even, ~Odd]

但 mypy 不喜歡它。

test5.py:8: error: Incompatible return value type (got "int", expected "Even")
test5.py:11: error: Incompatible return value type (got "int", expected "Odd")
Found 2 errors in 1 file (checked 1 source file)

所以我的問題是如何取悅 mypy 並仍然保持幫助的良好輸出? 除了#type: ignore

要進行此傳遞類型檢查,請改用NewType

from typing import NewType

Even = NewType('Even', int)
Odd  = NewType('Odd', int)


def make_even(n: int) -> Even:
    return Even(n*2)
    
def make_odd(n : int) -> Odd:
    return Odd(n*2 + 1)

def make_both(n: int) -> tuple[Even, Odd]:
    return make_even(n), make_odd(n)

但是現在help打印完全限定的名稱( __main__.Even在解釋器中)。 要解決此問題,您可以在未來使用字符串文字或annotations

...

def make_both(n: int) -> 'tuple[Even, Odd]':
    return make_even(n), make_odd(n)

或者

from __future__ import annotations
...

def make_both(n: int) -> tuple[Even, Odd]:
    return make_even(n), make_odd(n)

在第一種情況下, help輸出是

Help on function make_both in module __main__:

make_both(n: int) -> 'tuple[Even, Odd]'

在第二

Help on function make_both in module __main__:

make_both(n: 'int') -> 'tuple[Even, Odd]'

暫無
暫無

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

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