@@ -9,6 +9,68 @@ section has examples of cases when you need to update your code
9
9
to use static typing, and ideas for working
10
10
around issues if the type checker gets confused about your code.
11
11
12
+ .. _annotations_needed :
13
+
14
+ No errors reported for obviously wrong code
15
+ -------------------------------------------
16
+
17
+ There are several common reasons why obviously wrong code is not
18
+ flagged as an error.
19
+
20
+ - **No annotations on function containing the errors. ** Functions that
21
+ do not have any annotations (neither for any argument nor for the
22
+ return type) are not type-checked, and even the most blatant type
23
+ errors (e.g. ``2 + 'a' ``) pass silently. The solution is to add
24
+ annotations.
25
+
26
+ Example:
27
+
28
+ .. code-block :: python
29
+
30
+ def foo (a ):
31
+ return ' (' + a.split() + ' )' # No error!
32
+
33
+ This gives no error even though ``a.split() `` is "obviously" a list
34
+ (the author probably meant ``a.strip() ``). The error is reported
35
+ once you add annotations:
36
+
37
+ .. code-block :: python
38
+
39
+ def foo (a : str ) -> str :
40
+ return ' (' + a.split() + ' )'
41
+ # error: Unsupported operand types for + ("str" and List[str])
42
+
43
+ If you don't know what types to add, you can use ``Any ``, but beware:
44
+
45
+ - **One of the values involved has type ``Any``. ** Extending the above
46
+ example, if we were to leave out the annotation for ``a ``, we'd get
47
+ no error:
48
+
49
+ .. code-block :: python
50
+
51
+ def foo (a ) -> str :
52
+ return ' (' + a.split() + ' )' # No error!
53
+
54
+ The reason is that if the type of ``a `` is unknown, the type of
55
+ ``a.split() `` is also unknown, so it is inferred as having type
56
+ ``Any ``, and it is no error to add a string to an ``Any ``.
57
+
58
+ If you're having trouble debugging such situations,
59
+ :ref: `reveal_type() <reveal-type >` might come in handy.
60
+
61
+ Note that sometimes library stubs have imprecise type information,
62
+ e.g. the ``pow() `` builtin returns ``Any `` (see `typeshed issue 285
63
+ <https://github.com/python/typeshed/issues/285> `_ for the reason).
64
+
65
+ Another source of unexpected ``Any `` values is the
66
+ :ref: `"silent-imports" <silent-imports >` flag, which causes
67
+ everything imported from a module that cannot be located to have the
68
+ type ``Any `` (including classes inheriting from such). Sometimes
69
+ the :ref: `"disallow-subclassing-any" <disallow-subclassing-any >`
70
+ flag is helpful in diagnosing this. (Read up about these and other
71
+ useful flags like :ref: `"almost-silent" <almost-silent >` in
72
+ :ref: `command-line `.)
73
+
12
74
.. _silencing_checker :
13
75
14
76
Spurious errors and locally silencing the checker
0 commit comments