From PEP 563, it seems like there should be slight performance gains, as it solves
type hints are executed at module import time, which is not computationally free.
So...could/should I include from __future__ import annotations in every file in my package, or are there any reasons it should be excluded from some files?
TLDR: Some things will not work with from __future__ import annotations. Since a future version of Python will make postponed evaluation mandatory, code striving for forward compatibility should not rely on prompt evaluation in the first place.
Since from __future__ import annotations avoids the evaluation of type hints, anything that depends on evaluated type hints must explicitly evaluate type hints. This is usually not possible outside of top-level module or class scopes, unless locals are explicitly handled.
For example, functools.singledispatch cannot use type hints inside functions if annotation evaluation is postponed:
from __future__ import annotations
from typing import Type
from functools import singledispatch
def non_global_sdp(local_type: Type):
@singledispatch
def default(arg): print("default")
@default.register
def case_a(arg: local_type): print("case_a")
return default
cases = non_global_sdp(int) # NameError: name 'local_type' is not defined
The exact semantics of postponed evaluation of annotations and mandatory introduction version are still undecided. Of the current proposals the features of from __future__ import annotations are the most restrictive; any code that must work with future versions of Python should use from __future__ import annotations to avoid hidden dependencies on prompt evaluation.
__future__— Future statement definitions (Python 3.11)[1]
from __future__ import annotationswas previously scheduled to become mandatory in Python 3.10, but the Python Steering Council twice decided to delay the change (announcement for Python 3.10; announcement for Python 3.11). No final decision has been made yet. See also PEP 563 and PEP 649.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With