Pyright/mypy: "expr" 没有属性 "id"
Pyright/mypy: "expr" has no attribute "id"
代码:
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
s,请使用以下代码:
targets = ', '.join(t.id for t in assignment.targets if isinstance(t, ast.Name))
代码:
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
s,请使用以下代码:
targets = ', '.join(t.id for t in assignment.targets if isinstance(t, ast.Name))