mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Warning/Error for unassigned expressions/return values

Open samskiter opened this issue 1 year ago • 2 comments

Feature

Adding a warning or error if an expression is not assigned would encourage callers to handle return types and pick up on changes to APIs.

Pitch

Imagine you have this api:

def fleeb_the_foo() -> None:
    print("fleebing")

def main() -> None:
    fleeb_the_foo()

Then you change it later:

def fleeb_the_foo() -> Bool:
    print("I failed to fleeb!")
    return False

def main() -> None:
    fleeb_the_foo() # <<--- a warning or error here!

If you don't want to handle the warning/error:

def fleeb_the_foo() -> Bool:
    print("I failed to fleeb!")
    return False

def main() -> None:
    _ = fleeb_the_foo() # error is suppressed

This is already implemented to some degree with pylint for unassigned expressions with [expression-not-assigned]

str(42) == "42"  # [expression-not-assigned]

samskiter avatar Mar 27 '24 19:03 samskiter

I should also mention that there is precedent for this in order languages (C++ [[nodiscard]] and Swift: https://www.avanderlee.com/swift/discardableresult/)

samskiter avatar Mar 29 '24 08:03 samskiter

I might add, rust and ocaml also have this behaviour.

I think it would be good to make this check opt-in:

  • always: Raises an error if any non-assignment expression is not assigned
  • default: Raise an error only if a function or value with a @mustuse annotation is not assigned somewhere.

It would also be useful to have a ignore function in mypy with a simple implementation:

def ignore(expr: T) -> None:
  _ = expr

The annotation could look something like this:


@mustuse
def get_data() -> int:
  return ...

Or, it could be a part of the type directly:

def get_data() -> MustUse[int]
  ...

For the latter, it MustUse[T] should be able to just unify to T when it is actually used.

imagine-hussain avatar Jun 28 '24 06:06 imagine-hussain

Any hints on how to implement this?

samskiter avatar Nov 01 '24 15:11 samskiter