ENH: Opt-in option to show inferred variance in error messages
- Dominant language
- Rust
- Stars
- 7k
- Forks
- 516
- PR merge metrics
- No merged PRs in 30d
Description
### Describe the Bug
Debugging variance issues with PEP695 can be annoying (https://github.com/facebook/pyrefly/issues/2756), because there is no easy way to tell what the inferred variance is beyong writing explicit upcasting tests.
I would like to propose an opt-in setting that makes `reveal_type` and error messages include the inferred variance for all generic types, using `±` notation:[^1]
```python
from typing import Protocol, reveal_type
class Contravariant[T]:
def set(self, arg: T) -> None: ...
class Covariant[T]:
def get(self) -> T: ...
class Invariant[T]:
def get(self) -> T: ...
def set(self, arg: T) -> None: ...
def show(
contra: Contravariant[int],
cov: Covariant[int],
inv: Invariant[int],
) -> None:
reveal_type(contra) # Contravariant[-int] rather than Contravariant[int]
reveal_type(cov) # Covariant[+int] rather than Covariant[int]
reveal_type(inv) # Invariant[int] without + or -.
```
So, for instance we would also have
```python
reveal_type( frozenset({1,2,"a" }) ) # frozenset[+(int | str)]
````
[^1]: In [this thread](https://discuss.python.org/t/proposal-optional-explicit-covariance-contravariance-for-pep-695/35204) I suggested a typing feature to specify variance explicitly, even with PEP 695. But this may take a long time.
### Sandbox Link
https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0BlGFDAAddOIDGUVHDiCArsR584AYVrFUlCHFzoA2hu7bU2WABUAuojp0AxHUn6GlVADdtEDA3F27mDBgdAD6IbBhABRwwmAANHS4DAAWMJS2xlpu5jAWCQD0AJR0ALQAfIKxtoQ1fv6BwWFsMFExIglJqel0maY5eXRFpRVCItW16P50DaHhDK2xHSlpGZp9lgXF5ZVjdDWEdQFBs2zzIdGLicvdvdkbg1sjVXsT4lIycnQAggbWkQJKFQMdRrHR6QzWQq2BxOFxuTw6HyHabHGIMC7tOieKAKGC2CyPOgAOX0eJeBwklJmSkksnR%2BFsP1w2AAVjBJAwrISfmAoLhUJzEMjKDAGApKJN8HZHAAlUXi9AwTCMZgwOgAAyZrPZnPVnHk6CSdFkcAgbHQZlgjFwKOk2iVdBFYolKuIas1Bl5-M54hAcRACgY0DgJHIiBAjgAqkGoBAmHQwAp0ByIPo4G8sMcwLwaAKQugFDRsGlIgzOOgGIS4K4hZN-E6FQnRCAiYXi91gPgAL7N33%2Bsgi3mkQgMWhQCiOAAKpEHUFIdDQWDwUuc6EgbHFAtT6ApjiEauSDAYxDgiHy%2BQHQTnhF4bHyMHQ%2BUwuEkcHyq-Xm6D%2BnyCd4xs8aBLTVD8zS-bdEmIb90BDcQyBSfQSncNJTX0OgAF46GbABmQgAEYACZe3QEAu39VAU2QgAxaAYAoRccAIUNSKAA
### (Only applicable for extension issues) IDE Information
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.