python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.36k stars 2.81k forks source link

Cannot assert a callable returns `None` when it must return `None` #17568

Open cjw296 opened 3 months ago

cjw296 commented 3 months ago

Bug Report

mypy prevents you making assertions about callables that must return None when they're called. This is important as not everyone works in a type-checked context, and so library code must be robust to this. In my case, I have a chain of callables, the ones in the middle take iterables and return iterables, but the one at the start must take no arguments and the one at the end must consume the upstream iterable and return nothing.

To Reproduce

def returns_none() -> None:
    pass

assert returns_none() is None

Expected Behavior

No mypy complaints

Actual Behavior

"returns_none" does not return a value (it only ever returns None) [func-returns-value]

Your Environment

gandhis1 commented 3 months ago

The error is to prevent people from attempting to do things with the return values of functions that return None. Whether or not that thing is an assertion doesn't really seem relevant. As the point of Mypy is to statically verify things, supporting constructs used with dynamic type verification seem to be outside of the scope of Mypy. You can type: ignore[func-returns-value] if you need to.

At a minimum I'd argue this is a feature request, not a bug