Skip to content

Always complain if returning a value if annotated to return None #1509

Description

@JukkaL

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.

Activity

  1. gvanrossum commented on May 9, 2016

    @gvanrossum
    Member

    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.

  2. gnprice commented on Jul 29, 2016

    @gnprice
    Collaborator

    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.

  3. added this to the milestone on Aug 4, 2016
  4. removed this from the milestone on Mar 29, 2017
  5. AlexWaygood commented on Mar 24, 2022

    @AlexWaygood
    Member

    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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions