python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.44k stars 2.82k forks source link

Do not known how to call the issue. Please fix the subject line. #9567

Closed socketpair closed 2 years ago

socketpair commented 4 years ago
src = {
    'test': {
        'a': 1,
        'b': '2',
    },
}
{key: {**value, 'c': False} for key, value in src.items()}

gives:

main.py:7: error: Argument 1 to "update" of "dict" has incompatible type "Dict[str, object]"; expected "Mapping[str, bool]"
Found 1 error in 1 file (checked 1 source file)

but actually works as expected:

In [1]: src = { 
   ...:     'test': { 
   ...:         'a': 1, 
   ...:         'b': '2', 
   ...:     }, 
   ...: } 
   ...: {key: {**value, 'c': False} for key, value in src.items()}                                                                                                           
Out[1]: {'test': {'a': 1, 'b': '2', 'c': False}}

https://mypy-play.net/?mypy=latest&python=3.8&gist=b9e421adc95622a33aceae1f2b6fcc6e

socketpair commented 4 years ago

@JelleZijlstra ?

AlexWaygood commented 2 years ago

I'm closing this issue. It's very unclear what this code is meant to do, or how you expect mypy to cope with it.

Mypy emits many errors for things which will not necessarily cause type errors at runtime, and this is entirely deliberate.

socketpair commented 2 years ago

emm. Why not to ask me (topicstarter) ?

socketpair commented 2 years ago

@AlexWaygood Python code in the example has no typing errors. mypy incorrectly thinks that {**value, 'c': False} is Mapping[str, bool]

JelleZijlstra commented 2 years ago

Duplicate of #11604 in that case (and probably others)

AlexWaygood commented 2 years ago

@socketpair, this stackoverflow Q&A might be helpful: https://stackoverflow.com/questions/68803511/mypy-error-incompatible-types-in-assignment-expression-has-type-dictnothing

The issue is that your code here is pretty dynamic, so mypy doesn't know how to interpret the types of your variables. You can fix the error by adding type annotations.