Skip to content

methods not assignable to Protocol with __self__ property #10514

@jorenham

Description

@jorenham

After reading https://discuss.python.org/t/when-should-we-assume-callable-types-are-method-descriptors/92938/9, I was curious to see if I could write structural method type, dual to the nominal ones in the types stdlib. But I ran into a bit of an issue:

from typing import Protocol

class HasSelf(Protocol):
    @property
    def __self__(self, /) -> object: ...

class A:
    def f(self) -> None: ...

reveal_type(A.f.__self__)   # ✅ type[A]
reveal_type(A().f.__self__) # ✅ A
f1: HasSelf = A.f           # ❌ reportAssignmentType
f2: HasSelf = A().f         # ❌ reportAssignmentType
  • Type of "A.f.__self__" is "type[A]"
    
  • Type of "A().f.__self__" is "A"
    
  • Type "(self: A) -> None" is not assignable to declared type "HasSelf"
      "FunctionType" is incompatible with protocol "HasSelf"
        "__self__" is not present  (reportAssignmentType)
    
  • Type "() -> None" is not assignable to declared type "HasSelf"
      "FunctionType" is incompatible with protocol "HasSelf"
        "__self__" is not present  (reportAssignmentType)
    

pyright playground

And I'm guessing that "__self__" is not present is not meant in a spiritual-philosophical sense :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    addressed in next versionIssue is fixed and will appear in next published versionbugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions