1

I am trying to enable in my linter the style-error (if this is the most suitable name) that should arise when a function has a type hint but no return statement. For instance:

def do_stuff() -> int:
    a = 2
    # this function expect at the very least something to be returned
    # but no return statement is provided

I have looked at pylint, mypy and flake8 documentation but they seem to not support such error. Also, is there a linter capable of arising a type-error, that is, the function is supposed to return an int but is actually returning a str. For instance:

def do_stuff() -> int:
    a = 2
    return 'abc'
    # this function expect a int value to be returned
    # but str value is returned instead

I am using VSCode. I know that this is possible in PyCharm

E. Faslo
  • 325
  • 5
  • 19

2 Answers2

2

The plugin Pylance supports this kind of static type checks out of the box by using Pyright under the hood.

I am not sure if Pylint already supports the >Python 3.6 style of static typing. The documentation here suggests that it uses / used an extra extension module that parses the docstrings of the function for the return parameter.

Haini
  • 922
  • 2
  • 12
  • 28
  • Do I need to enable it as linter as well? – E. Faslo Apr 09 '21 at 15:11
  • I don't think so. At least my settings don't reflect the fact, I still have pylint set there. You just have to enable it as language server when prompted: ```Select Yes when prompted to make Pylance the default language server. ``` – Haini Apr 09 '21 at 15:19
0

Maybe a linter can do this! However, for both cases, and especially for your latter desire (raise complaints if you return the wrong type), I think you don't really want a linter, you want an actual static typechecker.

The most common implementation is called mypy, but Google also provides a less-strict typechecker called ptype - that might be a better fit for a codebase that isn't (yet) highly disciplined about type annotations.

sinback
  • 926
  • 5
  • 17