Python 静态类型:如何告诉静态类型检查器我的函数已经检查了类型?

问题描述 投票:0回答:1

我有以下代码:

ExprType: TypeAlias = int | str | datetime

def check_type(value: ExprType, expected_type: type[ExprType]):
    if not isinstance(value, expected_type):
        raise TypeError(f"Expected {expected_type}, but got {type(result)}.")

value: ExprType = 0

# ... more processing ...

if m := re.match("(\d+)"), text_var):
    check_type(value, int)
    value += int(m.group(1))

现在,在最后一行中,我确信

value
的旧值是一个整数,因为它是由
check_type
函数检查的。然而,VSCode (Pylance) 对此不太确定,并警告我:

Operator + is not supported for types ExprType and int.

如何告诉静态类型检查器变量的类型已经在上一行中检查过?

python static-analysis
1个回答
0
投票

各种类型的检查器有不同的禁用检查的方法。典型的方法是在行尾添加

# type: ignore
(例如,请参阅之前的 SO 答案Mypy 如何忽略源文件中的单行?)。

另一个可能有效的选择是在类型检查器抱怨的行之前放置一行类似

assert instance(value, int)
的行。根据我的经验,类型检查器并不总是深入函数调用来弄清楚函数调用之外会发生什么,但断言可以帮助为类型检查器提供有用的提示。

© www.soinside.com 2019 - 2024. All rights reserved.