Astroid:通过类型注释推断函数参数的类型

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

我正在尝试使用 Astroid 为 Pylint 编写自定义 linting 规则,但我对类型推断有点困惑。我有以下代码:

class ProtectedObject:
    def save():
        pass
                
def save_protected_object(obj: ProtectedObject) -> None:
    obj.save()

如果我将这段代码存储在变量中,并通过执行

astroid
将其提供给
func = astroid.extract_node(code)
,我会得到
FuncDef
save_protected_object
,正如我所期望的那样。然而,Astroid 似乎没有正确推断
obj
变量的类型 - 它忽略了类型注释。我也没有成功调用
func.infer()
func.args.args[0].infer()
- 后者只是告诉我函数参数的类型是
Uninferable

有什么方法可以让 Astroid 从类型注释中推断出函数参数的类型吗?

type-inference pylint astroid
1个回答
0
投票

astroid 不使用打字信息(因为 pylint 是在打字不存在时创建的),如果您执行以下操作:

class ProtectedObject:
    def save():
        pass
                
def save_protected_object(obj) -> None:
    obj.save()

a = ProtectedObject()
save_protected_object(a)

然后 astroid 将正确推断。请参阅https://github.com/pylint-dev/pylint/issues/4813

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