Skip to content

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

Open

Description

@alicederyn

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

Activity

  1. AlexWaygood commented on Mar 17, 2023

    @AlexWaygood
    Member

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

  2. alicederyn commented on Mar 17, 2023

    @alicederyn
    ContributorAuthor

    Actually it does now! See #13838

  3. AlexWaygood commented on Mar 17, 2023

    @AlexWaygood
    Member

    Actually it does now! See #13838

    Oh my bad! Thank you!

  4. alicederyn commented on Mar 17, 2023

    @alicederyn
    ContributorAuthor

    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.

  5. AlexWaygood commented on Mar 17, 2023

    @AlexWaygood
    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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions