File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change @@ -808,3 +808,55 @@ not necessary:
808
808
class NarrowerArgument (A ):
809
809
def test (self , t : List[int ]) -> Sequence[str ]: # type: ignore [ override ]
810
810
...
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.
You can’t perform that action at this time.
0 commit comments