如何用mypy注释具有额外属性的类型?

2024-10-03 06:22:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个ast.UnaryOp对象,但我手动添加了一个parent属性(请参见answer)。如何在函数中对此进行注释

我目前只拥有:

def _get_sim206(node: ast.UnaryOp):
    if isinstance(node.parent, ast.If):
        return False
    return True

但是mypy抱怨ast.UnaryOp没有parent属性(这是理所当然的)

我怎样才能告诉mypy node不是ast.UnaryOp而是ast.UnaryOp + parent attribute

我的尝试

我已经创建了自己的UnaryOp类,它有一个父属性。我可以将其用于类型转换:

class UnaryOp(ast.UnaryOp):
    def __init__(self, orig: ast.UnaryOp) -> None:
        self.op = orig.op
        self.operand = orig.operand
        self.lineno = orig.lineno
        self.col_offset = orig.col_offset
        self.parent: ast.Expr = orig.parent  # type: ignore

它的缺点是我需要在很多地方输入cast,并且我引入了Any。如果我能在某个地方声明该文件中的所有ast.*类型都有parent属性,我会更愿意这样做


Tags: selfnodereturn属性defcolastoffset
1条回答
网友
1楼 · 发布于 2024-10-03 06:22:42

作为一种解决方法,您可以使用带有@runtime_checkable修饰的protocolisinstance(),这将在运行时检查是否定义了所有协议成员,并确保静态正确性

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

相关问题 更多 >