Reputation: 748
I seem to get errors with the following piece of code using mypy
payload = {
'flag': 'good'
}
payload = payload['flag']
scheme: Dict[str, Dict[str, str]] = {
'a_string': {
'status': 'abc_string'
}
}
scheme.get(payload).get('status')
or
payload = {
'flag': 'good'
}
payload = payload['flag']
scheme = {
'a_string': {
'status': 'abc_string'
}
}
scheme.get(payload).get('status')
I get the following error:
error: No overload variant of "get" of "Mapping" matches argument type "Dict[str, Any]" scheme.get(payload).get('status')
But when the types are this:
payload = {
'flag': 'good'
}
payload = payload['flag']
scheme: Dict = {
'a_string': {
'status': 'abc_string'
}
}
scheme.get(payload).get('status')
It works fine.
Why does this behaviour happen?
Upvotes: 4
Views: 7998
Reputation: 8189
You should check all the errors raised by mypy.
src/test.py:5: error: Incompatible types in assignment (expression has type "str", variable has type "Dict[str, str]")
src/test.py:12: error: No overload variant of "get" of "Mapping" matches argument type "Dict[str, str]"
src/test.py:12: note: Possible overload variant:
src/test.py:12: note: def get(self, key: str) -> Optional[Dict[str, str]]
src/test.py:12: note: <1 more non-matching overload not shown>
Note how it complains on line 5 with Incompatible types in assignment
.
You should change your code to something like:
flag = payload['flag']
...
scheme.get(flag).get('status')
but then mypy will complain with:
src/test.py:12: error: Item "None" of "Optional[Dict[str, str]]" has no attribute "get"
indicating that you may be calling get
on None
, which happens because scheme.get(flag)
returns an Optional
.
Upvotes: 2