hasattr() performance is bad on a slot that has no value
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 36k
- PR merge metrics
- PR metrics pending
Description
Bug report
Bug description:
Compare these two timeit invocations:
$ python3.14 -m timeit -s 'class Test: pass' -s 't = Test()' 'hasattr(t,"x")'
10000000 loops, best of 5: 33.5 nsec per loop
$ python3.14 -m timeit -s 'class Test: __slots__ = ("x",)' -s 't = Test()' 'hasattr(t,"x")'
1000000 loops, best of 5: 241 nsec per loop
Observe that in the case where Test.x is a slot, hasattr takes 241 ns to return False while it only takes 33.5 ns when there is no Test.x slot.
Peter Bierma advised me to file an issue when I asked about this in Discourse.
CPython versions tested on:
3.14, 3.13, 3.12
Operating systems tested on:
Linux
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the two Python 3.14 timeit commands from the issue and compare the missing attribute case with the unvalued slot case. Trace the slot lookup and hasattr path responsible for the difference. Done means the unvalued-slot case is measurably improved without changing hasattr’s False result or existing behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- performance
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100