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

Python

6527 readers
1 users here now

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

📅 Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

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

founded 2 years ago
MODERATORS
9
submitted 2 years ago* (last edited 2 years ago) by [email protected] to c/python
 

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?

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 3 points 2 years ago* (last edited 2 years ago) (3 children)

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

[–] o11c 3 points 2 years ago (1 children)
from __future__ import annotations
[–] [email protected] 1 points 2 years ago

Thanks for the tip

[–] qwop 1 points 2 years ago (1 children)

You still need to import the type before using it in a stringified type annotation for it to be valid though, so you'd need the import in an if TYPE_CHECKING: block either way, no?

[–] [email protected] 2 points 2 years ago (1 children)

Yes, but if it’s in a TYPE_CHECKING block I can ONLY use the annotation with quotes*, which is why I only use that method if I must.

  • except with from __future__ import annotations as I’ve just learned.
[–] qwop 1 points 2 years ago

Ah yeah, I see what you meant.