File tree 1 file changed +5
-8
lines changed 1 file changed +5
-8
lines changed Original file line number Diff line number Diff line change @@ -260,17 +260,16 @@ imports to a module and those imports cause cycles that didn't exist
260
260
before. If those cycles become a problem when running your program,
261
261
there's a trick: if the import is only needed for type annotations in
262
262
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:
266
265
267
266
File ``foo.py ``:
268
267
269
268
.. code-block :: python
270
269
271
- from typing import List
270
+ from typing import List, TYPE_CHECKING
272
271
273
- if False :
272
+ if TYPE_CHECKING :
274
273
import bar
275
274
276
275
def listify (arg : ' bar.BarClass' ) -> ' List[bar.BarClass]' :
@@ -289,7 +288,5 @@ File ``bar.py``:
289
288
290
289
.. note ::
291
290
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
295
292
is ``False `` at runtime but ``True `` while type checking.
You can’t perform that action at this time.
0 commit comments