mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Report error if self has explicit type

Open JukkaL opened this issue 13 years ago • 6 comments

For example, the following program should not be accepted:

class A:
    def f(self: Any): pass

JukkaL avatar Dec 12 '12 14:12 JukkaL

Actually, having a self argument with an Any type should be accepted. This can be useful when adapting dynamically typed programs. However, the following are bad at least stylistically, and it would be useful to report them somewhow:

  • explicit, non-Any type for the self argument
  • missing self argument

Since the name of self is up to the programmer, we can't just complain if the first argument is not spelled 'self'. So this might be a good compromise: give a warning if the first argument of a method has an explicit type that is not Any.

Now we can also diagnose some cases of forgetting to include self, without having to assume that it is spelled self:

class A:
    def f(x: int) -> None: ...    # Explicit type, not any => warning

This does not strictly have to be an error. For example, consider the above example: if the function is only called as A.f the code could arguably be considered valid (though probably of questionable style).

JukkaL avatar Feb 11 '13 10:02 JukkaL

@JukkaL: I can do this one.

ashleyh avatar Feb 27 '16 09:02 ashleyh

Given the situation with #1586 I'm going to retag this as "needs discussion".

rwbarton avatar Jun 03 '16 18:06 rwbarton

I wonder if we could do something like this:

  • If the first arg is named self we assume it's going to be called as an instance method (assuming there's no @classmethod or @staticmethod) and the type of self should be compatible with the class (whatever that means)
  • If the first arg has another name, we're not sure; we allow any explicit type, but if there's no type we still assume it's an instance method (assuming the method is annotated at all)
  • If the method is not annotated we assume nothing, except if --check-untyped-defs is used; then we use the same heuristic (whether the first arg is named self)

gvanrossum avatar Jun 03 '16 20:06 gvanrossum

I think we can close this issue.

elazarg avatar Dec 08 '16 09:12 elazarg

Whoops! Indeed.

gvanrossum avatar Dec 08 '16 15:12 gvanrossum