Search code examples
pythonmypypython-typingpyright

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


Code:

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"

From typeshed:

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

Solution

  • Consider the following Code:

    x = [100]
    x[0] = 200
    

    Running the following ast inspection:

    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]))
    

    prints the following:

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

    So in this case ast.expr can be either ast.Name or _ast.Subscript. Only ast.Name has an id attribute.

    To use only ast.Names use the following code:

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