Type narrowing does not apply to default arguments in definition time
Open
Nobody has claimed this yet.
bug
topic-runtime-semantics
topic-variable-scope
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
The default values for function parameters are evaluated during definition, and late-bound defaults aren't a thing yet, so type narrowing should work for them just fine.
To Reproduce
# demo.py
from typing import Optional
foo: Optional[int] = 42
assert foo is not None
reveal_type(foo) # demo.py:5: note: Revealed type is "builtins.int"
def bar(arg: int = foo) -> None: # demo.py:7: error: Incompatible default for argument "arg" (default has type "Optional[int]", argument has type "int")
...
Expected Behavior
There should be no error.
Actual Behavior
demo.py:7: error: Incompatible default for argument "arg" (default has type "Optional[int]", argument has type "int")
Your Environment
- Mypy version used: 0.961 (compiled: yes)
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: 3.10.1
- Operating system and version: Ubuntu 20.04
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproduction in demo.py and run it with the reported Mypy setup to confirm that narrowing is lost for the default argument. Trace the handling of narrowed expressions used in function defaults, then add a regression test showing that the Optional[int] value narrowed by the assertion is accepted as an int default.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100