Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mypy types issue - Possible overload variant

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?

like image 987
apollowebdesigns Avatar asked Oct 16 '25 12:10

apollowebdesigns


1 Answers

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.

like image 97
Sebastian Kreft Avatar answered Oct 18 '25 00:10

Sebastian Kreft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!