Does mypy only type check a function if it declares a return type?

主宰稳场 提交于 2020-11-29 19:25:38

问题


The following file:

from typing import List

class A:

def __init__(self, myStr):
    self.chars: List[int] = list(myStr)

def toString(self):
    return "".join(self.chars)

typechecks (note chars should be List[str] not List[int]): ➜ Python python3 -m mypy temp.py => Success: no issues found in 1 source file, but the following one, where I declare the return type of toString, does:

from typing import List

class A:

def __init__(self, myStr):
    self.chars: List[int] = list(myStr)

def toString(self) -> str:
    return "".join(self.chars)

➜  Python python3 -m mypy temp.py
temp.py:9: error: Argument 1 to "join" of "str" has incompatible type "List[int]"; expected "Iterable[str]"
Found 1 error in 1 file (checked 1 source file)

Could anyone explain mypy's behaviour in this case? Why do I need to add the return type to the function to force mypy to correctly diagnose the problem? (it already has all necessary information: that chars is List[int] and join accepts Iterable[str])


回答1:


This behavior of mypy is by design. Mypy assumes that if a function signature is missing type hints, the user did not want that function to be type checked yet and so skips analyzing that function body.

This behavior is intended to make progressively adding type hints when working on large codebases easier: you end up being warned only about functions you've had a chance to examine and migrate instead of being hit with a wall of warnings up front.

If you don't like this behavior and would prefer that mypy tries type checking function bodies no matter what, pass in the --check-untyped-defs command line flag (or config file option).

Alternatively, if you'd like mypy to warn you when you forget to add a type signature, use the --disallow-untyped-defs and --disallow-incomplete-defs flags.

The --strict flag may also enable all three of these flags, among other ones. You can run mypy --help to double-check this for yourself.



来源:https://stackoverflow.com/questions/62265366/does-mypy-only-type-check-a-function-if-it-declares-a-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!