~<type> 是做什么的?
What does ~<type> do?
在编写代码时,我遇到了表达 ~<type>
类型的 linter(其中 <type>
不是 <type>
文学类型)。例如 self
.
class A:
def foo(self):
reveal_type(self) # reveals "~A"
我认为这意味着“A
或 A
的子类”;但是,我无法在网上找到有关它的任何信息。
此外,您不能在代码中使用此语法:
a: ~A # raises an exception: TypeError: bad operand type for unary ~: 'type'
如果 a
会被揭露,那将是 Unknown
。
我在 Mypy 文档中找不到它,但 Pyright 看起来很相似,它的 documentation 说:
Within the function, the type of self is printed with a tilde preceding the class name. This indicates that the type is a TypeVar bound to the class rather than the class itself.
所以我觉得Mypy对~Classname
的使用也是一样的
查看 source code,如果 TypeVar 是协变的,则打印 (repr) 前导“+”,如果是逆变,则打印“-”,如果不变(既不是协变也不是逆变),则打印“~”。
在编写代码时,我遇到了表达 ~<type>
类型的 linter(其中 <type>
不是 <type>
文学类型)。例如 self
.
class A:
def foo(self):
reveal_type(self) # reveals "~A"
我认为这意味着“A
或 A
的子类”;但是,我无法在网上找到有关它的任何信息。
此外,您不能在代码中使用此语法:
a: ~A # raises an exception: TypeError: bad operand type for unary ~: 'type'
如果 a
会被揭露,那将是 Unknown
。
我在 Mypy 文档中找不到它,但 Pyright 看起来很相似,它的 documentation 说:
Within the function, the type of self is printed with a tilde preceding the class name. This indicates that the type is a TypeVar bound to the class rather than the class itself.
所以我觉得Mypy对~Classname
的使用也是一样的
查看 source code,如果 TypeVar 是协变的,则打印 (repr) 前导“+”,如果是逆变,则打印“-”,如果不变(既不是协变也不是逆变),则打印“~”。