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 "int" cannot be assigned to type "int | str" #3865

Closed
etomarat opened this issue Jan 25, 2023 · 3 comments
Closed

Type "int" cannot be assigned to type "int | str" #3865

etomarat opened this issue Jan 25, 2023 · 3 comments
Assignees

Comments

@etomarat
Copy link

Hey! I've encountered a very annoying bug that keeps bothering me. Please help how to fix this?

Environment data

  • Language Server version: 2023.1.30 (pyright bf8ec313)
  • OS and version: macOS 12.1 (21C52)
  • Python version (& distribution if applicable, e.g. Anaconda): 3.10

Code Snippet

from typing import Optional, Dict, Union, Any

baz = {
    404: {'description': 'oh no...'},
}

def foo(bar: Optional[Dict[Union[int, str], Dict[str, Any]]] = None):
    pass

foo(baz)

Repro Steps

  1. Paste a code to editor

Expected behavior

everything fine

Actual behavior

image

@erictraut
Copy link
Contributor

The type of baz is dict[str, dict[int, str]], which isn't compatible with the declared type of the bar parameter in foo, so pylance is telling you about this type violation.

For more details about type declarations and generic types, refer to this documentation.

This gets a bit deep into type theory, but here are the details. The generic type dict accepts two type parameters, and both of them are "invariant", which means that the types must match exactly. That means dict[str, Any] is not type compatible with dict[str | int, Any] or vice versa.

@etomarat
Copy link
Author

@erictraut Thanks for your reply! What should I do if the "foo" function is provided by the "fastapi" package (router response argument). Explicitly specify type the "baz" variable like this?

baz: Optional[Dict[Union[int, str], Dict[str, Any]]] = {
    404: {'description': 'oh no...'},
}

It's getting too verbose. At the same time, "mypy" does not consider it an error if the type of the "baz" variable is not specified.

@erictraut
Copy link
Contributor

I don't have enough context about the problem you're solving to offer advice on how to fix the problem in your code.

When I run mypy on the code snippet at the top of this issue, it emits the same error as pyright.

error: Argument 1 to "foo" has incompatible type "Dict[int, Dict[str, str]]"; expected "Optional[Dict[Union[int, str], Dict[str, Any]]]"  [arg-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