Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypedDict errors on use of merge operator |= even if keys are correct #16244

Closed
RenDelaCruz opened this issue Oct 11, 2023 · 2 comments · Fixed by #16249
Closed

TypedDict errors on use of merge operator |= even if keys are correct #16244

RenDelaCruz opened this issue Oct 11, 2023 · 2 comments · Fixed by #16249
Labels
bug mypy got something wrong topic-typed-dict

Comments

@RenDelaCruz
Copy link

RenDelaCruz commented Oct 11, 2023

Bug Report

For TypedDict, mypy accepts the use of .update() using a dict with appropriate keys. However, using the merge operator |= for TypedDict gives an error.

To Reproduce

class Foo(TypedDict):
    key: int
    
foo: Foo = {
    "key": 1
}

foo.update({"key": 2}) # Ok!

foo |= {"key": 3}
# error: Incompatible types in assignment (expression has type "dict[str, object]", variable has type "Foo")  [assignment]

mypy Playground

Expected Behavior

Using merge operator |= on TypedDict should be allowed, since .update() is supported.

Actual Behavior

Errors when using |= on TypedDict, even though the given keys are appropriate. This effectively means that projects using mypy cannot use PEP 584 syntax.

@RenDelaCruz RenDelaCruz added the bug mypy got something wrong label Oct 11, 2023
@erictraut
Copy link

I think you meant for the last line in the code sample to be foo |= {"key": 3}. The value needs to be an int. With this fix, mypy still generates an error (a false positive).

@RenDelaCruz
Copy link
Author

Yup sorry, edited now from {"key": "3"} to {"key": 3}.

But yes, mypy still generates an error even though .update() is accepted.

sobolevn added a commit that referenced this issue Oct 23, 2023
Please, note that there are several problems with `__ror__` definitions.
1. `dict.__ror__` does not define support for `Mapping?` types. For
example:
```python
>>> import types
>>> {'a': 1} | types.MappingProxyType({'b': 2})
{'a': 1, 'b': 2}
>>> 
```
2. `TypedDict.__ror__` also does not define this support

So, I would like to defer this feature for the future, we need some
discussion to happen.
However, this PR does fully solve the problem OP had.

Closes #16244

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-typed-dict
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants