[英]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.但 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)
So my question is how to please mypy and still keep the nice output from help?所以我的问题是如何取悦 mypy 并仍然保持帮助的良好输出? beside
#type: ignore
I suppose除了
#type: ignore
To make this pass type checking, use NewType
instead:要进行此传递类型检查,请改用
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)
But now help
prints fully qualified names ( __main__.Even
in interpreter).但是现在
help
打印完全限定的名称( __main__.Even
在解释器中)。 To resolve this, you can use string literals or annotations
future:要解决此问题,您可以在未来使用字符串文字或
annotations
:
...
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
输出是
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]'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.