Skip to content

Treat TYPE_CHECKING = False as an internal const value #19734

Description

@Josverl

Description

In order to support type_checking, it is common to import types from the typing or typing_extension modules.

To minimize runtime impact; this is often done conditional :

TYPE_CHECKING = False
if TYPE_CHECKING:
    from typing import List, Optional, Union # Add all your types here 

While running type checking, TYPE_CHECKING is always True , so typecheckers see the imports, runtime avoids them.

Note: that while the spec mentions typing.TYPE_CHECKING in practice all current type checkers also support the bare TYPE_CHECKING to avoid needing to import the typing module completely.

While this limits runtime processing, the code is still emitted into the .mpy or memory.
If the parser/compiler could special case TYPE_CHECKING = False to be treated as / equivalent to : _TYPE_CHECKING = Const(False)
then these type checking guards, and the code branches inside them, would be completely removed from the emitted bytecode.
This would completely avoid runtime and firmware size overhead, exchanges for a additional complexity in the parser/compiler.

The same guard can be used multiple times, for instance to define abstract methods that can be used in static type checking, but do not grow the modules compiled size.

class SSD1306(framebuf.FrameBuffer):
    # ...
    if TYPE_CHECKING:
        def write_cmd(self, cmd: int) -> None: ...
        def write_data(self, buf: bytes) -> None: ...

Code Size

The goal for this feature is to allow gradual typing of MicroPython code , while avoiding the size or processing overhead.

Implementation

I hope the MicroPython maintainers or community will implement this feature,
as I'm not too familiar with the parser (yet)

Code of Conduct

Yes, I agree

Activity

  1. added
    enhancementFeature requests, new feature implementations
    py-coreRelates to py/ directory in source
    on Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementFeature requests, new feature implementationspy-coreRelates to py/ directory in source

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions