Specifying a default of `None` for `Dict.get()` results in a type of `Any` instead of `Optional[Any]`

Open
#4,359 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
compilers

Research direction

Start by reproducing the two examples in the issue and inspect mypy's handling of Dict.get() type inference. Trace the relevant type-checking path and add a regression test showing that an explicit None default does not become Any; done means the revealed and return types match the intended Optional behavior.

Written by the indexing model from the issue text.

Description

bug priority-1-normal topic-type-variables

Example:

from typing import Dict

def foo(x: Dict) -> str:
    result = x.get('foo', None)
    reveal_type(result)  # E: Revealed type is 'Any'
    return result
from typing import Dict

def foo(x:Dict) -> str:
    result = x.get('foo')
    reveal_type(result)  # E: Revealed type is 'Union[Any, builtins.None]'
    return result  # E: Incompatible return value type (got "Optional[Any]", expected "str")
Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.