Skip to content

Check type variable bounds of self types #2351

Open

Description

@JukkaL

As follow-up to #2193, check that if self is declared with a type variable type, the type variable has a compatible bound. For example, some of these should be rejected:

T = TypeVar('T')
TA = TypeVar('TA', bound='A')
TC = TypeVar('TC', bound='C')

class A:
    def f(self: T) -> T: ...  # Should be error
    def g(self: TC) -> TC: ...  # Should be error
    def h(self: TA) -> TA: ...  # OK

class C: pass

(We may also want to check variance, but it's a separate issue and less clear.)

Activity

  1. added this to the milestone on Oct 27, 2016
  2. elazarg commented on Oct 30, 2016

    @elazarg
    Contributor

    #2381 should reject TC, but will accept T. I don't think I understand why should T be rejected.

  3. elazarg commented on Oct 30, 2016

    @elazarg
    Contributor

    Another complication - if the function is overloaded, it is the union of the self-types that should be considered.

  4. removed this from the milestone on Mar 29, 2017
  5. elazarg commented on Apr 3, 2017

    @elazarg
    Contributor

    @JukkaL do you consider the current behavior problematic/incomplete?

  6. JukkaL commented on Apr 18, 2017

    @JukkaL
    CollaboratorAuthor

    I don't think that allowing T is incorrect, but it's likely almost always not what the programmer intended, so giving a warning about it seems reasonable. Otherwise there could a more mysterious error messages generated elsewhere. This is not a very important issue, though.

  7. gvanrossum commented on Apr 18, 2017

    @gvanrossum
    Member

    I've written code like this using just T. My assumption was that for that particular method, T would behave as if it had a bound of the containing class.

  8. elazarg commented on Apr 18, 2017

    @elazarg
    Contributor

    Me too. I think the assumption about implicit bounds is "infer" rather than "object".

  9. JukkaL commented on Apr 18, 2017

    @JukkaL
    CollaboratorAuthor

    Hmm inferring the bound might be reasonable thing, at least when there is no explicit conflicting bound. However, that's not how self types work right now, and it would be a little ad hoc.

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