Skip to content Skip to sidebar Skip to footer

How Do I Annotate A Type Which Has An Extra Attribute With Mypy?

I have an ast.UnaryOp object, but I manually added a parent attribute (see answer). How do I annotate this in a function? I currently simply have: def _get_sim206(node: ast.UnaryOp

Solution 1:

As a workaround you could use isinstance() with protocol decorated with the @runtime_checkable, that will check at runtime that all protocol members are defined and also ensure statical correctness.

from typing import Protocol, runtime_checkable, cast
import ast


@runtime_checkable
class ParentProto(Protocol):
    parent: ast.AST
    

def foo(node: ast.UnaryOp):
    if isinstance(node, ParentProto):
        # use node.parent
        p = node.parent
        l = node.lineno
# assignment
g = ast.UnaryOp()
cast(ParentProto, g).parent = ast.If()

Post a Comment for "How Do I Annotate A Type Which Has An Extra Attribute With Mypy?"