Without this change, mypy can't infer proper types for cases like
`d.get(k, [])` where it needs type context to infer the type of
`[]`. We add the value type to the second argument to `get` using
union types, and this provides the context. This doesn't affect
the effective signature of `get`, other than providing the type
context for mypy.
Also removed some related redundant method definitions where we can
just inherit the base class definition. This makes it easier to
keep the method signatures consistent.
Note that this requires a few mypy PRs before mypy will be able to
use this effectively:
* https://github.com/python/mypy/pull/2718
* https://github.com/python/mypy/pull/2715
This chage more closely matches the behavior of `get` at runtime. Users can pass whatever they want in to the default
parameter and it will be returned if the key is absent. Additionally, `get` should return an `Optional` if called with
only one parameter.
```python
z = {'a': 22}
reveal_type(z.get('b'))
reveal_type(z.get('b', 22))
reveal_type(z.get('b', 'hello'))
```
Before:
```shell
test_get_default.py:2: error: Revealed type is 'builtins.int*'
test_get_default.py:3: error: Revealed type is 'builtins.int*'
test_get_default.py:4: error: Revealed type is 'builtins.int*'
test_get_default.py:4: error: Argument 2 to "get" of "dict" has incompatible type "str"; expected "int"
```
After:
```shell
test_get_default.py:2: error: Revealed type is 'Union[builtins.int*, builtins.None]'
test_get_default.py:3: error: Revealed type is 'builtins.int'
test_get_default.py:4: error: Revealed type is 'Union[builtins.int, builtins.str*]'
```
* Make Mapping covariant.
Fixes#510.
This requires a `# type: ignore` on `__getitem__` and `get` because
mypy complains about covariant parameters.
FWIW typing.py needs to be changed too. (It was covariant in the
value but invariant in the key -- typeshed was invariant in both.)
* Delete outdated comment.
* Backpeddle a bit -- Mapping key type should not be covariant.
In Python, it's possible to use the `next` builtin method on file
objects produced by `open`. This change modifies `typing.IO` so this
usage will successfully typecheck.
This reverts commit d43adbe97e.
Here's a simple example of code that breaks with this PR:
from typing import Mapping, Dict, Tuple
a = {('0', '0'): 42} # type: Mapping[Tuple[str, str], int]
b = a.get(('1', '1'), 0)
This gives an error on the last line:
error: No overload variant of "get" of "dict" matches argument types [Tuple[builtins.str, builtins.str], builtins.int]