1
submitted 1 year ago* (last edited 1 year ago) by wasabi@feddit.de to c/python@programming.dev

After learning about TYPE_CHECKING i made it a habit to put all imports that were only needed for type checking into an if TYPE_CHECKING: guard. But now I am wondering if that is actually intended to be used like that. Checking whether an import is only needed at type checking time can get quite tedious and sometimes you run into situations were you introduced some code that made the import a requirement at runtime.

How do you use TYPE_CHECKING? Whenever it is possible or only when using it actually solves a circular import?

top 4 comments
sorted by: hot top controversial new old
[-] ALERT@sh.itjust.works 2 points 1 year ago

I only use it to avoid circular imports. Otherwise, I can import the type plainly.

[-] thomasloven@lemmy.world 1 points 1 year ago* (last edited 1 year ago)

I don’t like having to quote the types, so I use it exclusively for avoiding circular imports.

[-] o11c@programming.dev 1 points 1 year ago
from __future__ import annotations
[-] rev@ihax0r.com 1 points 1 year ago

Any time you need different behavior between static type checking and runtime.

in 3.10 I’m using it to work around issue with NamedTuple generics. typing_extensions.NamedTuple allows Generics at runtime but typing.NamedTuple doesn’t. But the type checker we are using doesn’t support typing_extensions.NamedTuple like it does for the typing version so we lie at type checking time to get the typing to make sense but have different runtime type because otherwise its a TypeError

this post was submitted on 06 Jul 2023
1 points (100.0% liked)

Python

6127 readers
84 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events

October 2023

November 2023

PastJuly 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS