Description
Bug report
Bug description:
Not sure if this bug is reported before.
FWIK, CPython's reveal_type
was introduced based on the motivation of the same features in type checkers. But I found out the behavior is inconsistent, at least between CPython, mypy, and pytype based on the cases in Python 3 Types in the Wild: A Tale of Two Type Systems.
Case 1:
a = 1
reveal_type(a)
a = 's'
reveal_type(a)
Case 2
a = [1]
reveal_type(a)
a.append('s')
reveal_type(a)
Case 3
class A:
attr = 1
a = A()
reveal_type(a.attr)
a.attr = 's'
reveal_type(a.attr)
reveal_type | Case1 | Case2 | Case3 |
---|---|---|---|
CPython | int, str | list, list | int, str |
mypy | int, assignment error | list[int], arg-type error | int, assignment error |
pytype | int, str | List[int], List[Union[int,str] | int, str |
For code without type annotations, the current behavior is closer to pytype. Case 2 is unclear, because CPython's reveal_type
doesn't show the types for the elements.
And even if I add type to the code to address mypy errors, the result is still inconsistent:
Case 1:
a: int|str = 1
reveal_type(a)
a = 's'
reveal_type(a)
Case 2
a: list[int|str] = [1]
reveal_type(a)
a.append('s')
reveal_type(a)
Case 3
class A:
attr: int|str = 1
a = A()
reveal_type(a.attr)
a.attr = 's'
reveal_type(a.attr)
reveal_type | Case1 | Case2 | Case3 |
---|---|---|---|
CPython | int, str | list, list | int, str |
mypy | Union[int,str], str | List[Union[int, str]], List[Union[int, str]] | Union[int,str], str |
pytype | Union[int,str], str | List[Union[int, str]], List[Union[int, str]] | int, str |
I don't know what's the best behavior, while reveal_type
in CPython may not be fully aligned with any type checker's type systems. Based on the motivation, will it make sense to align the behavior with at least mypy's reveal_type
?
CPython versions tested on:
3.11, 3.12
Operating systems tested on:
Linux, macOS