Skip to content

TypeVars on 'self' on an instance method are not bound to the instance type. #5416

Open

Description

@TheDreadedAndy

Describe the Bug

When a typevar is applied to 'self' in an instance method, Pyrefly "forgets" that self must be an instance of the class it is defined in. As best I can tell, the same happens for class methods (which is potentially the cause of #5410)

For the below example, pyrefly 1.4.0 reports that it cannot access the attribute baz for class object*. It seems pyrefly is typing self to Self@bin instead of Self@Bar

from typing import TypeVar
Self = TypeVar("Self")
class Bar:
    def baz(self: Self) -> Self:
        return self.__class__.__new__(self.__class__)

    def bin(self: Self) -> Self:
        return self.baz()

This is particularly problematic for python<3.11, since typing.Self did not exist and so TypeVars are the only way to annotate the return types of factory functions that may be inherited by child classes.

Sandbox Link

https://pyrefly.org/sandbox/?project=v2.I6HIhJZWMXmgEg3oGChfI0YJJBCjBAx0SAZzSoQFHighJCVWgfOCFbgkBKcIEAMzoYFzVXw82AygR4DJIbUcmicRwuAEADcamCKINxrkEE3MWFNWCIAIKEADAFheAaM7vRRYKgKjUS8mTxloaqpCRklJQbGVvj5Me35Run5qnn5KfnKxPooOfQVQAk0sS8wEl7Woxinkg1NZMdBYSpKLOiS1qONLLOqgtAJUgTf-AQ

(Only applicable for extension issues) IDE Information

No response

Activity

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions