Skip to content

Commit 8f0316f

Browse files
davidfstrgvanrossum
authored andcommitted
Docs: Replace "if False" trick with "if TYPE_CHECKING". (#2181)
1 parent 7683ee2 commit 8f0316f

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

docs/source/common_issues.rst

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -260,17 +260,16 @@ imports to a module and those imports cause cycles that didn't exist
260260
before. If those cycles become a problem when running your program,
261261
there's a trick: if the import is only needed for type annotations in
262262
forward references (string literals) or comments, you can write the
263-
imports inside ``if False:`` so that they are not executed at runtime.
264-
The reason this works is that mypy (currently) does not analyze
265-
unreachable code like this. Example:
263+
imports inside ``if TYPE_CHECKING:`` so that they are not executed at runtime.
264+
Example:
266265

267266
File ``foo.py``:
268267

269268
.. code-block:: python
270269
271-
from typing import List
270+
from typing import List, TYPE_CHECKING
272271
273-
if False:
272+
if TYPE_CHECKING:
274273
import bar
275274
276275
def listify(arg: 'bar.BarClass') -> 'List[bar.BarClass]':
@@ -289,7 +288,5 @@ File ``bar.py``:
289288
290289
.. note::
291290

292-
It is possible that in the future, mypy will change its dead code
293-
analysis and this trick will stop working. We will then offer an
294-
alternative, e.g. a constant defined by the ``typing`` module that
291+
The ``TYPE_CHECKING`` constant defined by the ``typing`` module
295292
is ``False`` at runtime but ``True`` while type checking.

0 commit comments

Comments
 (0)