Skip to content

[red-knot] respect TYPE_CHECKING even if not imported from typing #15722

@carljm

Description

@carljm

Description

In order to avoid the runtime cost of importing typing module, some users use a pattern like this:

TYPE_CHECKING = False
if TYPE_CHECKING:
    from typing import ...

Where the type checker should recognize the name TYPE_CHECKING and treat it as True for type checking. Mypy and pyright both support this.

This is of course a bit ugly because we're recognizing an arbitrary name wherever it's used, but in practice the name is so distinctive that this doesn't seem to cause a lot of trouble.

It can be supported in a general way with a config option that allows specifying arbitrary names that should always be considered as builtin constants with some type, but this isn't usable for a library that can't control its users' type checker configuration.

Ideally we would specify a more principled way to do this (though that might also not be practically worth the community churn.)

But the use case is valid, and we should support it the same way pyright and mypy do, to avoid adding a migration barrier.

Metadata

Metadata

Assignees

No one assigned

    Labels

    tyMulti-file analysis & type inference

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions