python - Pyright/mypy : "expr" has no attribute "id"

标签 python python-3.x mypy type-annotation pyright

代码:

def extract_assignment(assignment: ast.Assign) -> Dict[str, LINES_RANGE]:
    targets = ', '.join(t.id for t in assignment.targets)

pyright/mypy:

error: "expr" has no attribute "id"

来自typeshed :

class Assign(stmt):
    targets: typing.List[expr]
    value: expr

最佳答案

考虑以下代码:

x = [100]
x[0] = 200

运行以下 ast 检查:

import ast

code = """
x = [100]
x[0] = 200
"""

root = ast.parse(code)
for node in ast.walk(root):
    if isinstance(node, ast.Assign):
        print(type(node.targets[0]))

打印以下内容:

<class '_ast.Name'>
<class '_ast.Subscript'>

因此,在本例中,ast.expr 可以是 ast.Name_ast.Subscript。只有 ast.Name 具有 id 属性。

要仅使用 ast.Name,请使用以下代码:

targets = ', '.join(t.id for t in assignment.targets if isinstance(t, ast.Name))

关于python - Pyright/mypy : "expr" has no attribute "id",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63995481/

相关文章:

Python:如何将从列表中以某个字母开头的元素复制到新列表中或从列表中删除不以字母开头的元素

python - 类型提示指定类型的集合

python-3.x - Jupyter Notebook 中缺少模块导入时出错

python - mypy 提示 Incompatible return value type (got "Optional[str]"expected "str") when a function can only return str

python - 如何在类型提示系统中使用通用(高级)类型变量?

python - Python Django-如何同时支持Socket和API

python - pipenv install --system 但仅供用户使用

Python:无法连接 'str' 和 'int' 对象错误

python-3.x - 从配置文件读取的'\r\n'不等于python的解释或 '\r\n'

python - Mypy 提示 __setitem__ 签名