Ensure FloatRange clamping always returns a float#3548
Closed
sarathfrancis90 wants to merge 2 commits into
Closed
Conversation
FloatRange._clamp returned the stored boundary directly for non-open bounds. The boundaries are kept exactly as passed to the constructor, so a value written as an int literal (e.g. FloatRange(0, 1, clamp=True)) caused clamping to return an int instead of a float, breaking the documented return type. Coerce the boundary through the number class so a clamped value is always a float. fixes pallets#3547
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
FloatRange(..., clamp=True)could return anintinstead of afloatwhen an out-of-range value was clamped to a boundary that had been written as an integer literal.FloatRangeis declared as_NumberRangeBase[float]/FloatParamTypeand is documented to return afloat, so returning aninthere violates the type contract.Root cause
The constructor stores the boundaries exactly as they were passed in, so
FloatRange(0, 1, clamp=True)keepsself.min/self.maxas Pythonints.FloatRange._clampreturned the stored boundary verbatim for non-open bounds, propagating thatintto the caller.Fix
Coerce the boundary through
self._number_class(which isfloatforFloatRange) before returning it, so a clamped value is always afloat. In-range values andIntRangeare unaffected.Tests
Added
test_float_range_clamp_returns_float, parametrized over a value above and below the range, assertingtype(result) is float. The existing clamp tests usefloatboundary literals (0.5/1.5) andtest_rangecompares with==(where1 == 1.0), so they did not catch this. The new test fails onmain(AssertionError: <class 'int'> is float) and passes with the change.fixes #3547
.. versionchanged::entries in relevant code docs.