Skip to content

gh-137855: Lazy import inspect module in dataclasses#144387

Open
danielhollas wants to merge 16 commits intopython:mainfrom
danielhollas:dataclass-lazy-inspect
Open

gh-137855: Lazy import inspect module in dataclasses#144387
danielhollas wants to merge 16 commits intopython:mainfrom
danielhollas:dataclass-lazy-inspect

Conversation

@danielhollas
Copy link
Contributor

@danielhollas danielhollas commented Feb 2, 2026

inspect module is slow to import (see #117865) and is dragging down dataclasses with it.

There are currently only two uses of inspect in dataclasses, but they are a bit tricky to inline since they are on a direct code path when the @dataclass decorator is executed.

  1. inspect.signature is used to autogenerate class docstring (if one is not provided already)
  2. inspect.unwrap is used in a rather esoteric code path only for slotted classes, added in gh-90562: Improve zero argument support for super() in dataclasses when slots=True #124692)

For 1. I have used a descriptor protocol to generate the __doc__ attribute on demand (this is my first time messing with descriptors, apologies if I overlooked something).

For 2. can be deferred by calling the unwrap functions only when really necessary (and hopefully this path is not common)

Benchmarks

./python -Ximporttime -c "import dataclasses"

Before

image
hyperfine -w 10 './python -c "import dataclasses"' 
Benchmark 1: ./python -c "import dataclasses"
  Time (mean ± σ):      19.2 ms ±   2.1 ms    [User: 14.9 ms, System: 4.1 ms]
  Range (min … max):    16.6 ms …  24.1 ms    154 runs

After

image
hyperfine -w 10 './python -c "import dataclasses"' 
Benchmark 1: ./python -c "import dataclasses"
  Time (mean ± σ):      15.2 ms ±   1.8 ms    [User: 11.2 ms, System: 3.7 ms]
  Range (min … max):    12.9 ms …  19.4 ms    212 runs

Overall seems to be a solid 20-30% improvement.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review performance Performance or resource usage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants