Skip to content

Commit 3b2e114

Browse files
authored
Discuss unreachable code as a common issue (#8899)
Documented unreachable code issues and --warn-unreachable usage
1 parent 1ae0855 commit 3b2e114

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

docs/source/common_issues.rst

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,3 +808,55 @@ not necessary:
808808
class NarrowerArgument(A):
809809
def test(self, t: List[int]) -> Sequence[str]: # type: ignore[override]
810810
...
811+
812+
Unreachable code during typechecking
813+
------------------------------------
814+
815+
Sometimes a part of the code can become unreachable, even if not immediately obvious.
816+
It is important to note that in such cases, that part of the code will *not* be type-checked
817+
by mypy anymore. Consider the following code snippet:
818+
819+
.. code-block:: python
820+
821+
class Foo:
822+
bar:str = ''
823+
824+
def bar() -> None:
825+
foo: Foo = Foo()
826+
return
827+
x:int = 'abc'
828+
829+
It is trivial to notice that any statement after ``return`` is unreachable and hence mypy will
830+
not complain about the mis-typed code below it. For a more subtle example, consider:
831+
832+
.. code-block:: python
833+
834+
class Foo:
835+
bar:str = ''
836+
837+
def bar() -> None:
838+
foo: Foo = Foo()
839+
assert foo.bar is None
840+
x:int = 'abc'
841+
842+
Again, mypy will not throw any errors because the type of ``foo.bar`` says it's ``str`` and never ``None``.
843+
Hence the ``assert`` statement will always fail and the statement below will never be executed.
844+
Note that in Python, ``None`` is not a null-reference but an object of type ``NoneType``. This can
845+
also be demonstrated by the following:
846+
847+
.. code-block:: python
848+
849+
class Foo:
850+
bar: str = ''
851+
852+
def bar() -> None:
853+
foo: Foo = Foo()
854+
if not foo.bar:
855+
return
856+
x:int = 'abc'
857+
858+
Here mypy will go on to check the last line as well and report ``Incompatible types in assignment``.
859+
860+
If we want to let mypy warn us of such unreachable code blocks, we can use the ``--warn-unreachable``
861+
option. With this mypy will throw ``Statement is unreachable`` error along with the line number from
862+
where the unreachable block starts.

0 commit comments

Comments
 (0)