pythonvisual-studio-codepylancepyright

How to find type of a Python variable when hovering the mouse cursor over a variable in Visual Studio Code?


I want to find out its type when hovering over a variable with the mouse, but this does not work. Does anyone know how to do this? For example, when hovering over x, it writes some kind of Literal, although I directly declared the type of the variable as int.

enter image description here


Solution

  • In the tooltip, Literal refers to typing.Literal, which is a special form used to define a type that is the set of all given literal values.

    Easy to see that Literal[1] is a subtype of int, Literal['foo'] is a subtype of str and so on.

    In this case, the type checker (Pyright) is able to infer a more specific type for x, so it went ahead and did just that. This is a feature, not a bug. Depending on the flow, this type might change:

    (playground)

    x = 1235
    reveal_type(x)      # Literal[1235]
    
    for _ in range(0):
        x += 2
        reveal_type(x)  # int
    
    reveal_type(x)      # int
    

    It should also be noted that this might or might not be the case with other type checkers; that is, this is implementation-specific. Take Mypy for example:

    (playgrounds: Mypy, Pyright)

    x1: int
    x1 = 1235
    reveal_type(x1)  # pyright => Literal[1235]
                     # mypy    => int
    
    x2: int = 1235
    reveal_type(x2)  # pyright => Literal[1235]
                     # mypy    => int
    
    x3 = 1235
    reveal_type(x3)  # pyright => Literal[1235]
                     # mypy    => int
    
    x4 = 1233 + 2
    reveal_type(x4)  # pyright => Literal[1235]
                     # mypy    => int
    

    As far as I know, there is currently no setting to control this behaviour.