Skip to content

Why do the docs often have types using strings and if TYPE_CHECKING? #2146

Closed Answered by JacobCoffee
ceigey asked this question in Q&A
Discussion options

You must be logged in to vote

The use of if TYPE_CHECKING: along with stringized annotations is a common pattern in Python type hinting to avoid circular dependencies and to reduce the runtime overhead associated with importing large modules.

Sometimes, type annotations can create circular import dependencies, where module A imports module B and module B imports module A. Using if TYPE_CHECKING: with stringized annotations ensures that the import is only considered by type checkers like mypy and not at runtime. This breaks the circular dependency. You can see an example of this in the Python docs on if TYPE_CHECKING

aslo.. if a module is heavy and only needed for type checking, using if TYPE_CHECKING: makes sure it is…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@JacobCoffee
Comment options

@Goldziher
Comment options

@ceigey
Comment options

Answer selected by Alc-Alc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants