9
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?

you are viewing a single comment's thread
view the rest of the comments
[-] o11c@programming.dev 0 points 1 year ago

You should have part of your test harness perform a separate import of every module. If your module is idempotent (most good code is) you could do this in a single process by cleaning sys.modules I guess ... but it still won't be part of your pytest process.

Static analyzers can only detect some cases, so can't be fully trusted.

I've also found there are a lot of cases where performant Python code has to be implemented in a distinct way from what the type-checker sees. You can do this with aggressive type: ignore but I often find it cleaner to use separate if blocks.

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

Python

6224 readers
22 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