|
9 | 9 | \listingToolOutput{lists:lists_error:mypy}{% |
10 | 10 | The results of static type checking with \mypy\ of the program given in \cref{lst:lists:lists_error}.}% |
11 | 11 | % |
| 12 | +\begin{sloppypar}% |
12 | 13 | Recently, we learned that static code analysis tools can help us to discover subtle problems in our programs. |
13 | 14 | Obviously, when dealing with more complex datastructures like lists, there are also more potential problems, more mistakes that one could make. |
14 | 15 | Let us look at the very short example program \programUrl{lists:lists_error} in \cref{lst:lists:lists_error}. |
15 | 16 | The program consists of only two lines, \pythonil{my_list: list[str] = list([1, 2, 3])} and \pythonil{print(my_list)}. |
16 | 17 | It does not have any \emph{error} in the strict sense. |
17 | | -We can execute it just fine and it will produce the output \textil{[1, 2, 3]} as shown in \cref{exec:lists:lists_error}. |
18 | | - |
| 18 | +We can execute it just fine and it will produce the output \textil{[1, 2, 3]} as shown in \cref{exec:lists:lists_error}.% |
| 19 | +\end{sloppypar}% |
| 20 | +% |
19 | 21 | However, upon closer inspection, we discover some issues. |
20 | 22 | In a first step, we would apply \mypy~(as~\cref{ut:mypy}) to check for problems with the types of variables. |
21 | 23 | And indeed, \cref{exec:lists:lists_error:mypy} shows us \emph{three} errors! |
|
83 | 85 | The corrected version of~\cref{lst:lists:lists_error}, taking into account the information given by \mypy\ in \cref{exec:lists:lists_error:mypy} and \ruff\ in \cref{exec:lists:lists_error:ruff}.}{}% |
84 | 86 | % |
85 | 87 | % |
| 88 | +\begin{sloppypar}% |
86 | 89 | In \cref{lst:lists:lists_fixed} we implement the three recommendations from the two tools as program \programUrl{lists:lists_fixed}. |
87 | 90 | We change the \pgls{typeHint} of the list to \pythonil{list[int]}, which solves the type confusion that \mypy\ discovered. |
88 | 91 | We remove the useless copying of the list as \ruff\ recommended. |
89 | 92 | Finally, we add a proper \pgls{docstring} at the top of the file, in which we even document the changes we applied. |
90 | 93 | The output \cref{exec:lists:lists_fixed} of the new program remains the same. |
91 | 94 | But now, both tools are satisfied, as shown in \cref{exec:lists:lists_fixed:mypy,exec:lists:lists_fixed:ruff}. |
92 | | -And our program is much clearer and faster. |
93 | | - |
| 95 | +And our program is much clearer and faster.% |
| 96 | +\end{sloppypar}% |
| 97 | +% |
94 | 98 | \gitExec{exec:lists:lists_fixed:mypy}{\programmingWithPythonCodeRepo}{.}{_scripts_/mypy.sh collections lists_fixed.py}% |
95 | 99 | \listingToolOutput{lists:lists_fixed:mypy}{% |
96 | 100 | The results of static type checking with \mypy\ of the program given in \cref{lst:lists:lists_fixed}.}% |
|
0 commit comments