Code expected to be unreachable #145
-
Sometimes, code is expected to be unreachable. eg. class Foo:
...
class Bar:
...
something: Foo | Bar = some_function_call()
if isinstance(something, Foo):
...
elif isinstance(something, Bar):
...
else:
raise TypeError(f"unexpected type: {something.__class__.__name__}") Is there a good way to handle this, to tell basedmypy that that raise line should always be unreachable. It would be good to not just ignore it, but have some way of saying that if the line later becomes unreachable, it is an error. A harder problem - is it possible to also check that the unreachable |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Expect this feature in python 3.11(or in If you are expecting a line to be unreachable all you have to do is annotate that line with if False:
message = "unreachable" # type: ignore[unreachable]
raise RuntimeError(message) Also note that this is unrelated to basedmypy, all this functionality is in mypy. There is an issue to create a dedicated function for this purpose #147 in basedmypy/basedtyping. Original commentMypy treats unreachable lines that raise exceptions as reachable: playground link There is a tracking issue here
The stub is the only source of truth, if it can return def some_function_call() -> Foo | Bar | Baz: ... If you don't know explicitly what it could return, you could type it something like one of these: def some_function_call() -> Foo | Bar | object: ...
def some_function_call() -> Foo | Bar | Any: ... Or are you describing a different scenario?
Not sure what you mean, if the line is currently reachable and becomes unreachable later it will become an error. |
Beta Was this translation helpful? Give feedback.
-
To clarify, i'm wanting to know how to annotate this correctly (is there some annotation to say that I expect that else block to be unreachable). I'm thinking of 3 scenarios:
I want scenario 1 and 2 to pass (it believes the stub), and scenario 3 to fail type checking (to alert me that the else block is now reachable, and I now need to update my code to handle 'Baz'). |
Beta Was this translation helpful? Give feedback.
Expect this feature in python 3.11(or in
typing_extensions
) withtyping.assert_never
python/typing/issues/735If you are expecting a line to be unreachable all you have to do is annotate that line with
# type: ignore[unreachable]
, this only applies to the first unreachable line of a branch. Note that there is an issue where this will not be reported on lines withraise
statements, to work around this, just put a filler line, eg:Also note that this is unrelated to basedmypy, all this functionality is in mypy.
There is an issue to create a dedicated function for this purpose #147 in basedmypy…