我有一个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
属性,我会更愿意这样做
作为一种解决方法,您可以使用带有@runtime_checkable修饰的protocol的
isinstance()
,这将在运行时检查是否定义了所有协议成员,并确保静态正确性相关问题 更多 >
编程相关推荐