Skip to content

NamedTuple should not satisfy Protocol with mutable fields #5293

Closed

Description

@pnachum

The following code doesn't produce a type error, but will crash at runtime, because the named tuple's fields cannot be set

from typing import NamedTuple
from typing_extensions import Protocol

class HasX(Protocol): 
    x: str
    
class A(NamedTuple):
    x: str

a: HasX = A("foo")
a.x = "bar"

Since HasX requires x to be settable, A should not be a structural subtype of HasA.

Activity

  1. ilevkivskyi commented on Jun 29, 2018

    @ilevkivskyi
    Member

    OK, the solution is super-simple here. Since named tuple variables are "artificial" (auto-generated), and therefore are always created directly as a Var with is_property set to True, they are not identified as immutable by protocol check (it looks for a property decorator).

    So it would be just one line fix in subtypes.get_member_flags, we need to add a check for v.is_property in this code:

        # just a variable
        if isinstance(v, Var):
            flags = {IS_SETTABLE}
    

    Would you like to make a PR?

  2. pnachum commented on Jun 29, 2018

    @pnachum
    Author

    I'll leave that to people smarter than me 😄.

  3. added a commit that references this issue on Jun 29, 2018
    028bd91
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugpriority-1-normaltopic-protocols

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions