'What does ~<type> do?
When writing code I have encountered my linter expressing the type of ~<type> (where <type> is a type not <type> literary). An example of this is self.
class A:
def foo(self):
reveal_type(self) # reveals "~A"
I assume this means "A or a subclass of A"; however, I was unable to find any information about it online.
Also, you can't use this syntax in code:
a: ~A # raises an exception: TypeError: bad operand type for unary ~: 'type'
If a would have been revealed it would be Unknown.
Solution 1:[1]
I can't find it in the Mypy documentation, but Pyright seems similar, and its documentation says:
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.
So I think Mypy's use of ~Classname is the same.
Solution 2:[2]
Looking at the source code, TypeVars are printed (repr) with a leading "+" if they are covariant, "-" if contravariant, and "~" if invariant (neither covariant nor contravariant).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Waygood |
| Solution 2 | wjandrea |
