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

final TypedDict with total=False does not allow clear/popitem #14914

Open
alicederyn opened this issue Mar 17, 2023 · 5 comments
Open

final TypedDict with total=False does not allow clear/popitem #14914

alicederyn opened this issue Mar 17, 2023 · 5 comments
Labels
bug mypy got something wrong topic-final PEP 591 topic-typed-dict

Comments

@alicederyn
Copy link

Bug Report

PEP-589 disallows clear and popitem on TypedDicts, even if all known keys are not required, as there may be other required keys due to structural subtyping. However, a @final-decorated TypedDict cannot be structurally subtyped, so these methods should be available.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=7d42af8206cb1e25a53673bdf4e99df1

from typing import TypedDict, final

@final
class A(TypedDict, total=False):
    k: int

a: A = {"k": 1}
a.clear()

Expected Behavior

No errors

Actual Behavior

error: "A" has no attribute "clear"  [attr-defined]

Your Environment

  • Mypy version used: 1.0.0
  • Python version used: 3.11
@AlexWaygood
Copy link
Member

Kiiiiiind of a duplicate of #7981, in that mypy doesn't currently have any special handling for TypedDicts decorated with @final :)

@alicederyn
Copy link
Author

Actually it does now! See #13838

@AlexWaygood
Copy link
Member

Actually it does now! See #13838

Oh my bad! Thank you!

@alicederyn
Copy link
Author

alicederyn commented Mar 17, 2023

What return type should popitem have?

  • Tuple[str, Any]
  • Tuple[str, Union[ValueType1, ValueType2, ...]]
  • Union[Tuple[Literal["key1"], ValueType1], Tuple[Literal["key2"], ValueType2], ...]

Normally it would have to be the first one, but because the TypedDict is final, we know the complete possible set of key/value types. The third would be the most accurate but also the most costly to work with and hardest to read if any errors came up.

@AlexWaygood
Copy link
Member

I'd personally go with option (2). Silently inferring Any would feel pretty unfortunate here, in my opinion, given that we've got enough information to infer a better type. But the third option feels unnecessarily complex, at least for now.

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-final PEP 591 topic-typed-dict
Projects
None yet
Development

No branches or pull requests

2 participants