【问题标题】:Pyright/mypy: "expr" has no attribute "id"Pyright/mypy:“expr”没有属性“id”
【发布时间】:2020-09-21 15:35:03
【问题描述】:

代码:

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

pyright/mypy:

错误:“expr”没有属性“id”

来自typeshed

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

【问题讨论】:

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


    【解决方案1】:

    考虑以下代码:

    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.Names,请使用以下代码:

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

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 1970-01-01
      • 2023-02-01
      • 2011-05-13
      • 2021-03-02
      • 1970-01-01
      • 2018-01-20
      • 2015-02-19
      • 1970-01-01
      相关资源
      最近更新 更多