PEP 749: Implementing PEP 649

Is there any work planned to improve the import time of annotationlib?

I’m bringing this up partly due to the discussion around PEP-781 as with the current implementation in 3.14.0a6 the import time of typing has increased significantly.

Comparing start times of 3.13 and 3.14 with and without typing imports:

Benchmark 1: ~/.pyenv/versions/3.14.0a6/bin/python -c ''
  Time (mean ± σ):      17.7 ms ±   4.5 ms    [User: 13.3 ms, System: 4.3 ms]
  Range (min … max):    12.8 ms …  29.3 ms    50 runs
 
Benchmark 2: ~/.pyenv/versions/3.13.2/bin/python -c ''
  Time (mean ± σ):      18.1 ms ±   4.7 ms    [User: 14.0 ms, System: 4.0 ms]
  Range (min … max):    12.6 ms …  28.3 ms    50 runs
 
Benchmark 3: ~/.pyenv/versions/3.14.0a6/bin/python -c 'import typing'
  Time (mean ± σ):      35.4 ms ±   5.6 ms    [User: 29.5 ms, System: 5.9 ms]
  Range (min … max):    27.0 ms …  47.8 ms    50 runs
 
Benchmark 4: ~/.pyenv/versions/3.13.2/bin/python -c 'import typing'
  Time (mean ± σ):      25.3 ms ±   4.7 ms    [User: 20.9 ms, System: 4.4 ms]
  Range (min … max):    19.2 ms …  39.2 ms    50 runs
 
Summary
  ~/.pyenv/versions/3.14.0a6/bin/python -c '' ran
    1.02 ± 0.37 times faster than ~/.pyenv/versions/3.13.2/bin/python -c ''
    1.43 ± 0.45 times faster than ~/.pyenv/versions/3.13.2/bin/python -c 'import typing'
    2.00 ± 0.59 times faster than ~/.pyenv/versions/3.14.0a6/bin/python -c 'import typing'

This largest chunk of this seems to be due to the usage of ast which is mostly required for the _Stringifier class. As this class isn’t always going to be needed it would be nice if it was possible to avoid this.

My initial thought would be that you could split annotationlib.py into a package with annotationlib/__init__.py and annotationlib/_stringifier.py, move the definition of _Stringifier into the latter file and defer the import of this until the class is needed. The one remaining use of ast in ForwardRef.__forward_arg__ could then also use a deferred import. I don’t know if you already have another solution in mind.

2 Likes