Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

type hint with "Union" operator doesn't work properly #3624

Closed
djccnt15 opened this issue Nov 14, 2022 · 1 comment
Closed

type hint with "Union" operator doesn't work properly #3624

djccnt15 opened this issue Nov 14, 2022 · 1 comment

Comments

@djccnt15
Copy link

Environment data

  • Language Server version: 2022.11.20 (pyright 470188d0)
  • OS and version: windows 11
  • Python version (& distribution if applicable, e.g. Anaconda): 3.10, 3.11

Code Snippet

I made simple function which returns identity matrix like below

vector = list[float | int]
matrix = list[vector]

def mat_identity(n: int) -> matrix:
    """
    returns n by n sized identity matrix
    """

    I = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
    return I

Repro Steps

just type the code

Expected behavior

obviously the function shouldn't have any problem, as code below returns no error at all

vector = list[float | int]
matrix = list[vector]

m: matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Actual behavior

pylance warn error like below

Expression of type "list[list[int]]" cannot be assigned to return type "matrix"
  "list[list[int]]" is incompatible with "matrix"
    TypeVar "_T@list" is invariant
      "list[int]" is incompatible with "vector"
        TypeVar "_T@list" is invariant
          Type "int" cannot be assigned to type "float | int"
@djccnt15 djccnt15 changed the title nested type hint with "Union" operator doesn't work properly type hint with "Union" operator doesn't work properly Nov 14, 2022
@erictraut
Copy link
Contributor

erictraut commented Nov 14, 2022

Yes, this behavior is correct. To understand why, please review this documentation about static type concepts.

There are two simple options for eliminating the type violation error:

  1. Do not assign the intermediate value to variable I. Move the return keyword directly before the list comprehension. This allows pylance to use bidirectional type inference to infer the correct return type.
  2. Supply a type declaration for intermediate variable I (I: matrix). This once again allows pylance to use bidirectional type inference to determine the intended type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants