Skip to content

Consistency of reveal_type results with other type checkers #113255

Description

@gkirchou

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_typeCase1Case2Case3
CPythonint, strlist, listint, str
mypyint, assignment errorlist[int], arg-type errorint, assignment error
pytypeint, strList[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_typeCase1Case2Case3
CPythonint, strlist, listint, str
mypyUnion[int,str], strList[Union[int, str]], List[Union[int, str]]Union[int,str], str
pytypeUnion[int,str], strList[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

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions