]> git.ipfire.org Git - thirdparty/Python/cpython.git/commit
[3.12] gh-117983: Defer import of threading for lazy module loading (GH-120233) ...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 3 Jul 2024 21:09:00 +0000 (23:09 +0200)
committerGitHub <noreply@github.com>
Wed, 3 Jul 2024 21:09:00 +0000 (21:09 +0000)
commit81f575427edf497ee9d2dafe97986d3b9ed85ee5
tree7c37358d9d8dc085bc43b1146ffb041b0dcb7161
parent399e516d28f1604ef52baf52546b4c71e7cd4c84
[3.12] gh-117983: Defer import of threading for lazy module loading (GH-120233) (GH-121350)

gh-117983: Defer import of threading for lazy module loading (GH-120233)

As noted in gh-117983, the import importlib.util can be triggered at
interpreter startup under some circumstances, so adding threading makes
it a potentially obligatory load.
Lazy loading is not used in the stdlib, so this removes an unnecessary
load for the majority of users and slightly increases the cost of the
first lazily loaded module.

An obligatory threading load breaks gevent, which monkeypatches the
stdlib. Although unsupported, there doesn't seem to be an offsetting
benefit to breaking their use case.

For reference, here are benchmarks for the current main branch:

```
❯ hyperfine -w 8 './python -c "import importlib.util"'
Benchmark 1: ./python -c "import importlib.util"
  Time (mean ± σ):       9.7 ms ±   0.7 ms    [User: 7.7 ms, System: 1.8 ms]
  Range (min … max):     8.4 ms …  13.1 ms    313 runs
```

And with this patch:

```
❯ hyperfine -w 8 './python -c "import importlib.util"'
Benchmark 1: ./python -c "import importlib.util"
  Time (mean ± σ):       8.4 ms ±   0.7 ms    [User: 6.8 ms, System: 1.4 ms]
  Range (min … max):     7.2 ms …  11.7 ms    352 runs
```

Compare to:

```
❯ hyperfine -w 8 './python -c pass'
Benchmark 1: ./python -c pass
  Time (mean ± σ):       7.6 ms ±   0.6 ms    [User: 5.9 ms, System: 1.6 ms]
  Range (min … max):     6.7 ms …  11.3 ms    390 runs
```

This roughly halves the import time of importlib.util.
(cherry picked from commit 94f50f8ee6872007d46c385f7af253497273255a)

Co-authored-by: Chris Markiewicz <effigies@gmail.com>
Lib/importlib/util.py
Misc/NEWS.d/next/Library/2024-06-07-10-10-32.gh-issue-117983.NeMR9n.rst [new file with mode: 0644]