Description
Why is this needed?
Source files that have from __future__ import annotations
are not taking full advantage of the import. Namely, this import enables PEP 563 (Postponed Evaluation of Annotations), which allows:
- usage of
if typing.TYPE_CHECKING:
for types to be used only by the type checker and no need to quote type names (unless being used in forward references) - use of PEP 585 (Type Hinting Generics In Standard Collections) in Python < 3.9
- use of PEP 604 (Allow writing union types as X | Y) in Python < 3.10
Looking at the files with this import we see that not all of them have if typing.TYPE_CHECKING:
, which could have been the initial motivation to add the import, and they have mixed usages of PEP 585 and PEP 604.
Some other files do have if typing.TYPE_CHECKING:
without the import and are quoting the type names instead.
Also, I see some if typing.TYPE_CHECKING:
is being used for the types defined in the mypy_boto3_* packages, which are dev dependencies and in these cases this makes sense.
Which area does this relate to?
Static typing
Suggestion
We already have a constraint:
- The import of types from the mypy_boto3_* packages must be inside
if typing.TYPE_CHECKING:
.
And here are suggestions (see https://stackoverflow.com/a/53455562/2654518):
- Use
from __future__ import annotations
instead of quoting types imported insideif typing.TYPE_CHECKING:
. - Using both
from __future__ import annotations
andif typing.TYPE_CHECKING:
can improve the startup performance since less packages are imported during runtime. Although optimizing performance really only makes sense if we have benchmarks first.
Also:
Looks like the current code does not have a clear direction on how to follow these suggestions. I'd say it's more consistent and cleaner to have a guideline. So, here are some decisions that could be made:
- Do we use
from __future__ import annotations
instead of quoting types that have been imported insideif typing.TYPE_CHECKING:
? I'd say YES since we're already using the import in some files. - Do we use
from __future__ import annotations
andif typing.TYPE_CHECKING:
in all files?- Even if we choose YES, should we at least skip the example files?
- Do we use PEP 585 and PEP 604 in files using
from __future__ import annotations
? I'd say definitely YES if we choose YES for question 2.
Acknowledgment
- This request meets Powertools for AWS Lambda (Python) Tenets
- Should this be considered in other Powertools for AWS Lambda languages? i.e. Java, TypeScript, and .NET
Metadata
Metadata
Assignees
Labels
Type
Projects
Status