Skip to content

Mypy doesn't ensure self types are reasonable #2374

Closed

Description

@ddfisher

For example, this typechecks cleanly:

class C:
    def f(self: str) -> None:
        self.capitalize()

Related to #2193.

Activity

  1. ddfisher commented on Oct 28, 2016

    @ddfisher
    CollaboratorAuthor
  2. elazarg commented on Oct 29, 2016

    @elazarg
    Contributor

    Based on the above issue, this seems like a good idea... :)

  3. JukkaL commented on Oct 31, 2016

    @JukkaL
    Collaborator

    This looks like a dupe of #16, but I'll leave this open since there's a PR that references this.

    One thought from the discussion at #16: It may be reasonable to have a first argument (at least one not spelled as self) with an arbitrary annotation, but that function will not be a proper instance method and should only be callable within the class body. Example:

    class A:
        def f(x: str) -> int:   # ok
            return int(x)
    
        a = f('123')  # ok
    
    A().f()  # error, f is not a method
    

    #16 has more discussion.

  4. gvanrossum commented on Oct 31, 2016

    @gvanrossum
    Member
  5. elazarg commented on Oct 31, 2016

    @elazarg
    Contributor

    IMO, ideally we would only allow use of such a function from within the class' scope. We would report an error for functions that are used from the outside (as suggested by Jukka), and also for functions that are unused from the inside.

    However, personally I would vote for requiring an explicit hint for such functions, keeping the policy and implementation simpler.

  6. gvanrossum commented on Oct 31, 2016

    @gvanrossum
    Member
  7. elazarg commented on Nov 1, 2016

    @elazarg
    Contributor

    I was thinking about type: ignore... But of course it can be something else. And you can use @staticmethod I guess.

  8. gvanrossum commented on Nov 1, 2016

    @gvanrossum
    Member

    Static methods can't be called without a class.

    >>> @staticmethod
    ... def f(): pass
    ...
    >>> f()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'staticmethod' object is not callable
    >>>
    
  9. added a commit that references this issue on Nov 2, 2016
    a90841f
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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions