Warning/Error for unassigned expressions/return values
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]
I should also mention that there is precedent for this in order languages (C++ [[nodiscard]] and Swift: https://www.avanderlee.com/swift/discardableresult/)
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@mustuseannotation 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.
Any hints on how to implement this?