Skip to content

Protocol does not accept subtype as class attribute #14963

Closed as not planned
Closed as not planned

Description

@blhsing

Run:

from typing import Protocol

class Str(str):
    pass

class A:
    field: Str

class B(Protocol):
    field: str

def f(arg: B):
    pass

f(A())

and get:

main.py:15: error: Argument 1 to "f" has incompatible type "A"; expected "B"  [arg-type]
main.py:15: note: Following member(s) of "A" have conflicts:
main.py:15: note:     field: expected "str", got "Str"
Found 1 error in 1 file (checked 1 source file)

Why is subtype not accepted as a class attribute of a protocol? Does this not adhere to the Liskov Substitution Principle?

Please help explain the rationale behind such an implementation or if this is actually a bug.

Activity

  1. JelleZijlstra commented on Mar 27, 2023

    @JelleZijlstra
    Member

    This is because you made a writable attribute. Given a variable arg: B, it is legal to do arg.field = "x", but that is not compatible with type A.

    To make a read-only protocol field, use @property.

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