gh-106498: Fix an extreme case in colorsys.rgb_to_hls
#106530
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
colorsys.rgb_to_hls(1, 1, 0.9999999999999999)
raisesZeroDivisionError
now (this probably is the ONLY case). Not sure if it's worth fixing, but I think "correct" in all cases is more important than "very slightly faster in theory".This optimization is originally introduced in #23306, using the benchmark given in the PR, there's no observable performance regression with the extra check.
Benchmark Code
Another possible implementation is to do a try-except block for the division. As
try
is almost no cost now, it would be theoretically faster than the current one. The return value would be different (a near white color can be represented in many forms in hls space). I prefer the current solution as it's easy to understand with the comment, but I do not oppose the other way.