Mypy doesn't complain about this code that returns a value in a function declared to return None, since the return value is Any:
def f() -> None:
return g() # oops, but no error
def g():
return 1
I think that mypy could complain about the return statement even if the value has type Any. The current behavior is not inconsistent or incorrect, but probably not optimal.
If you're saying that in a function declared as -> None, any return statement with an expression should always be flagged as an error, I agree with you, though it's technically a style choice, and I've occasionally seen code that uses this knowing the function being called is also returning None, just as a shorthand for
g()
return
IIRC there was also some discussion with @ddfisher about the opposite -- whether in a function declared to return an Optional type, a bare return (or falling off the end) is acceptable style or not.
Added label depends-on/strict-optional because I think anything we do here will probably look different in the strict-optional world from the no-strict-optional world, and any discussion should probably be in the context of the strict-optional world which we intend to be the only world in the future.
Activity
gvanrossum commented on May 9, 2016
If you're saying that in a function declared as -> None, any return statement with an expression should always be flagged as an error, I agree with you, though it's technically a style choice, and I've occasionally seen code that uses this knowing the function being called is also returning None, just as a shorthand for
IIRC there was also some discussion with @ddfisher about the opposite -- whether in a function declared to return an Optional type, a bare return (or falling off the end) is acceptable style or not.
gnprice commented on Jul 29, 2016
Added label depends-on/strict-optional because I think anything we do here will probably look different in the strict-optional world from the no-strict-optional world, and any discussion should probably be in the context of the strict-optional world which we intend to be the only world in the future.
AlexWaygood commented on Mar 24, 2022
Mypy now correctly emits an error if --warn-return-any and/or --strict are specified (though the default behavior is still that it emits no errors).
Is this sufficient? — can this issue now be closed?