Specify `TYPE_CHECKING = False` without typing import

Assigning to __debug__ fails, which might be the inspiration here. I imagine it would also be relevant for implementing compiler optimisations, and @methane mentioned bytecode size above. Allowing __type_checking__ = False (and updating type checkers to recognise it) would mean that adoption could be much quicker, though.

I suppose the question is how important/useful is the invariant of __type_checking__ is False. I implemented the code that @hauntsaninja linked to as a (mildly awful) workaround for trying to identify the source of annotations with PEP 563 [1], where reloading a module after an initial import with TYPE_CHECKING = True can work and mean that we’re able to resolve more type annotations at runtime (as Sphinx imports the code that it is auto-documenting).

I’m not aware of many other use-cases for setting TYPE_CHECKING to True at runtime, though, so it may be that the gains from specifying the new constant as always False outweigh the drawbacks.

A


  1. I haven’t had time yet to properly investigate, but my hope is that PEP 649/749 makes things better ↩︎

1 Like