Skip to content

Commit 1541653

Browse files
committed
errorcodes: added optional code missing-return-annotation and enforce in semantic analysis file; added tests as well
1 parent 1b8841b commit 1541653

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

mypy/errorcodes.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,5 +319,12 @@ def __hash__(self) -> int:
319319
default_enabled=False,
320320
)
321321

322+
MISSING_RETURN_ANNOTATION = ErrorCode(
323+
"missing-return-annotation",
324+
"Function has no return type annotation",
325+
"Optional",
326+
)
327+
328+
322329
# This copy will not include any error codes defined later in the plugins.
323330
mypy_error_codes = error_codes.copy()

mypy/semanal.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757

5858
from mypy import errorcodes as codes, message_registry
5959
from mypy.constant_fold import constant_fold_expr
60-
from mypy.errorcodes import PROPERTY_DECORATOR, ErrorCode
60+
from mypy.errorcodes import PROPERTY_DECORATOR, ErrorCode, MISSING_RETURN_ANNOTATION
6161
from mypy.errors import Errors, report_internal_error
6262
from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type
6363
from mypy.message_registry import ErrorMessage
@@ -926,6 +926,25 @@ def visit_func_def(self, defn: FuncDef) -> None:
926926
with self.inside_except_star_block_set(value=False):
927927
self.analyze_func_def(defn)
928928

929+
# Missing return annotation check (optional error code)
930+
from mypy.types import CallableType
931+
932+
if (
933+
# Makes sure return type is not specified, ignores lambdas and special cases
934+
isinstance(defn.type, CallableType)
935+
and defn.type.ret_type is None
936+
and any(arg.type_annotation is not None for arg in defn.arguments)
937+
and defn.name != "__init__"
938+
and not defn.is_lambda
939+
and not defn.is_overload
940+
):
941+
self.msg.fail(
942+
f'Function "{defn.name}" has no return type annotation',
943+
defn,
944+
code=MISSING_RETURN_ANNOTATION,
945+
)
946+
947+
929948
def function_fullname(self, fullname: str) -> str:
930949
if self.current_overload_item is None:
931950
return fullname
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[case test_missing_return_annotation_ok]
2+
# flags: --enable-error-code missing-return-annotation
3+
def g(x: int) -> int:
4+
return x
5+
6+
[case test_missing_return_annotation_off_by_default]
7+
def h(x: int):
8+
return x # no error expected, since code is opt-in

0 commit comments

Comments
 (0)