MyPy - “赋值中的类型不兼容(表达式的类型为 None,变量的类型为 ...)"; [英] MyPy - "Incompatible types in assignment (expression has type None, variable has type ...)"
问题描述
我有下面的函数,给定一个 'a-02/b-03/foobarbaz_c-04'
形式的字符串,将提取 a 之后的数字em>、b 和 c.问题是,对于我的用例,输入字符串可能不包含 c,这样就没有要提取的数字.
I've got the following function, which given a string of the form 'a-02/b-03/foobarbaz_c-04'
, will extract the digits after a, b and c. The issue is that, for my use case, the input strings may not contain c, such that there will be no digits to extract.
代码如下:
from typing import Tuple, Optional
def regex_a_b_c(name: str) -> Tuple[int, int, Optional[int]]:
a_b_info = re.search('a-(\d\d)/b-(\d\d)/', name)
a, b = [int(a_b_info.group(x)) for x in range(1, 3)]
c_info = re.search('c-(\d\d)', name)
if c_info:
c = int(c_info.group(1))
else:
c = None
return a, b, c
我遇到的问题是,尽管试图明确最后一个返回参数是一个 Optional[int]
,但我无法让我的 linter 停止抱怨变量 c.
The issue I have is that, despite trying to make it clear that the last return argument is an Optional[int]
, I can't get my linter to stop complaining about the variable c.
我在 c = None
行收到一条警告,内容为:
I get a warning at the line c = None
that says:
赋值中的类型不兼容(表达式的类型为 None,变量有类型 int)
Incompatible types in assignment (expression has type None, variable has type int)
我该如何解决这个问题?
How can I solve the issue?
推荐答案
当你第一次使用一个变量时,mypy 基本上会根据它看到的第一个赋值来推断它的类型.
When you use a variable for the first time, mypy will essentially infer its type based on the very first assignment it sees.
所以在这种情况下,行 c = int(_info.group(1))
首先出现,因此 mypy 决定类型必须是 int
.然后,当它看到 c = None
时,它随后会抱怨.
So in this case, the line c = int(_info.group(1))
appears first, so mypy decides that the type must be int
. It then subsequently complains when it sees c = None
.
解决此限制的一种方法是仅使用预期类型向前声明变量.如果您使用的是 Python 3.6+ 并且可以使用变量注释,您可以这样做:
One way of working around this limitation is to just forward-declare the variable with the expected type. If you are using Python 3.6+ and can use variable annotations, you can do so like this:
c: Optional[int]
if c_info:
c = int(c_info.group(1))
else:
c = None
或者更简洁,像这样:
c: Optional[int] = None
if c_info:
c = int(c_info.group(1))
如果您需要支持旧版本的 Python,您可以使用基于注释的语法对类型进行注释,如下所示:
If you need to support older versions of Python, you can annotate the type using the comment-based syntax, like so:
c = None # type: Optional[int]
if c_info:
c = int(c_info.group(1))
rje 的建议:
if c_info:
c = int(c_info.group(1))
return a, b, c
else:
return a, b, None
...也是合理的.
这篇关于MyPy - “赋值中的类型不兼容(表达式的类型为 None,变量的类型为 ...)";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!