Sequence[Mapping[str, Any]] won't allow dict with different layouts
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When a function takes Sequence[Mapping[str, Any]] and a call is made with dictionaries having different fields, a cryptic error is reported that seems to indicate strange affinity for same type even for different field types.
This use is typical for passing in a Mongo DB pipeline list, which is flagged as an error, while there is none, like in this method:
To Reproduce
mypy --strict --check-untyped-defs --strict-equality \
--warn-redundant-casts --warn-incomplete-stub \
--warn-unreachable --install-types \
--non-interactive app.py
def fn(p: Sequence[Mapping[str, Any]]) -> None:
pass
p = [{"x": 1}, {"y": "A"}]
fn(p) # <-- error reported
fn([{"x": 1}, {"y": "A"}]) # <-- no error
q = [{"x": "1"}, {"y": "A", "z": "3"}]
fn(q) # <-- no error (but will be if any number is unquoted)
The error is reported for p:
app.py:6: error: Argument 1 to "fn" has incompatible type "List[object]"; expected "Sequence[Mapping[str, Any]]" [arg-type]
Expected Behavior
Sequence[Any] may be used to pass in different types and should allow dictionaries with arbitrarily different layouts for Sequence[Mapping[str, Any]].
Actual Behavior
mypy enforces some internal logic that cannot be described as enforcing same layout, which is indicated by q having very different dictionaries and not triggering this error. However, if any of the numbers in q is unquoted, the error is reported for the last fn call.
Your Environment
- Mypy version used:
mypy 1.2.0 (compiled: yes) - Mypy command-line flags: see above
- Mypy configuration options from
mypy.ini(and other config files): None (not used) - Python version used: Python 3.10.10
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
Reproduce the report by putting the examples in app.py and running the documented mypy command with Python 3.10. Compare the inferred types for the assigned list and the inline list, then trace the relevant type-checking behavior. Done means dictionaries with different layouts are accepted when passed as Sequence[Mapping[str, Any]] without weakening unrelated type checks.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100