After the great work of everyone involved in PEP 810, I would like to propose a new idea that is similar and somewhat changes a bit of the PEP itself, which is the introduction of the type
keyword for imports that are only used for typing reasons.
This would be beneficial for people reading the code to understand that the import is only there for type checking reasons, and it will not ever be evaluated, similar to lazy imports proposed in PEP 810, but the code won’t ever need to do the reification of the import, because the code will never call the imported item.
For example:
from typing import type Dict
I understand there is a type
keyword already implemented, so I’m unsure if there is a compatibility issue here, so maybe another keyword should be used instead. I thought of the following:
typeonly
typedef
ty
(although clashes with the ty project)
This implementation could have the following benefits:
- Type imports would never be evaluated
- Optionally, libs could be bundled without type imports, lowering the size of the distribution (?)
- Improve readability, as it would be clear the imports are there only for type checking
- Possibly improve linters and static type checkers, depending on the implementation
- Removes
TYPE_CHECKING
requirement for cases where imports could cause a recursive dependency - Multiple codebases import typings without the
TYPE_CHECKING
check - this would be beneficial for the 1st point
My idea is that this would move the type imports after all the other imports in the file, as such:
import json
from datetime import datetime
from typing import type Dict
For backwards compatibility, possibly the CPython implementation could replace it with the current TYPE_CHECKING
check.
I should make it clear that this is only useful after (if) PEP 810 is implemented, as this could create a confusion between real lazy imports, and imports that are tagged as lazy but are just there for type checking reasons.
Would be great to hear ideas, suggestions, questions or general feedback.
Thanks!
See also: PEP 810 discussion