简体   繁体   中英

mypy Incompatible return value type for numeric types

consider this example

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)

its output is nice and all, exactly like I want it

Help on function make_both in module __main__:

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

but mypy doesn't like it.

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)

So my question is how to please mypy and still keep the nice output from help? beside #type: ignore I suppose

To make this pass type checking, use NewType instead:

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)

But now help prints fully qualified names ( __main__.Even in interpreter). To resolve this, you can use string literals or annotations future:

...

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

or

from __future__ import annotations
...

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

In first case help output is

Help on function make_both in module __main__:

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

in second

Help on function make_both in module __main__:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM