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?

    • qwop@programming.dev
      link
      fedilink
      English
      arrow-up
      1
      ·
      1 year ago

      Same, I think it’s more common only to use when necessary.

      The main case I can think of to use it more is for performance to save an import at runtime, but I don’t think that’s really valid, especially since the fact you’re using the type annotation suggest the module would have been used elsewhere anyway so the import would be cached.

      The argument against using anywhere is that it could be misleading as your editor may indicate that the import is definited even if it wouldn’t be at runtime. Not sure if things like pylance have special handling to avoid this, would have to check…