Error on dict construction from iterable items
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Attempting to construct a mapping from objects that are designed to be constructed into dict items results in an error.
To Reproduce
Run mypy on this file:
from typing import Dict
class MyObject(str):
"""
>>> tuple(MyObject('G'))
('G', 71)
"""
def __iter__(self):
return iter((self, ord(self)))
def get_mapping() -> Dict[str, int]:
"""
>>> get_mapping()
{'a': 97, 'b': 98}
"""
items = MyObject('a'), MyObject('b')
return dict(items)
In this file, MyObject implements __iter__ to return a key/value pair such that a dict can be constructed from an iterable of MyObjects.
Note that python -m doctest dictable.py passes.
Expected Behavior
Mypy should honor dict's behavior to produce pairs from objects if they're iterable and accept any iterable of objects that when iterated on produce pairs of compatible types.
Actual Behavior
dictable.py:18: error: Argument 1 to "dict" has incompatible type "Tuple[MyObject, MyObject]"; expected "Iterable[Tuple[str, int]]"
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 0.790
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.9.0
- Operating system and version: macOS 11.0
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 by running mypy on the reproduced example in dictable.py and compare it with the passing doctest behavior. Trace how the dict construction is typed, then verify that compatible iterable item objects are accepted while the existing type-checking behavior remains intact.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100