Skip to content

Better type for self in untyped functions #4637

Closed

Description

@gsalgado

Running mypy --check-untyped-defs against the code below will give an error only for method m2():

/tmp/foo.py:6: error: "Dict[str, str]" has no attribute "unknown_method"

When in fact I'd expect a similar error for the self.unknown_method() line.

class Foo:
    def m(self):
        self.unknown_method()
    def m2(self):
        d = dict(foo='bar')
        d.unknown_method()

However, if I add a type annotation to method m(): def m(self) -> None:, I do get the error I expected:

/tmp/foo.py:3: error: "Foo" has no attribute "unknown_method"
/tmp/foo.py:6: error: "Dict[str, str]" has no attribute "unknown_method"

Activity

  1. JukkaL commented on Feb 26, 2018

    @JukkaL
    Collaborator

    The type of self is Any if you don't have an annotation -- all unannotated arguments are given Any types. However, maybe self should be an exception and work similarly to annotated functions. The cls argument of class methods is also currently Any in unannotated methods even when using --check-unyped-defs.

  2. gsalgado commented on Feb 26, 2018

    @gsalgado
    Author

    Hmm, yeah, I think that'd make sense, in the same way that self gets assigned the correct type (Foo) when the method has just a return type annotation (def m(self) -> None:)

  3. gvanrossum commented on Feb 26, 2018

    @gvanrossum
    Member
  4. changed the title [-]Method body not checked even with --check-untyped-defs[/-] [+]Better type for self in untyped functions[/+] on Mar 7, 2018
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