Return non-finite floats unchanged from naturaldelta#343
Open
eeshsaxena wants to merge 1 commit into
Open
Conversation
naturaldelta() documents that a value which cannot be converted to a
number is returned unchanged. float("nan") was handled because int(nan)
raises ValueError, but float("inf")/float("-inf") raised an uncaught
OverflowError from int(value), which the except clause omitted.
Catch OverflowError alongside ValueError/TypeError around the int()
guard so infinity is returned unchanged, symmetric with nan. The catch
is scoped to the int() conversion only, so a finite value too large for
datetime.timedelta still raises OverflowError from timedelta(), as
documented.
Fixes python-humanize#333
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.
Summary
Fixes #333.
naturaldelta()documents that a value which cannot be converted to a number is "returned unchanged."float("nan")is handled (itsint()raisesValueError, which is caught), butfloat("inf")/float("-inf")raise an uncaughtOverflowErrorfromint(value), because theexcept (ValueError, TypeError)clause omittedOverflowError. The behavior was asymmetric and contradicted the docstring.Before
After
Implementation note
The catch is scoped to the
int(value)guard only. A finite value too large to convert to adatetime.timedelta(e.g.1e40) still raisesOverflowErrorfromtimedelta(), as documented underRaises:- this is verified by an added test so the non-finite guard does not swallow the legitimate overflow.Tests
Added
test_naturaldelta_nonfinite(nan, inf, -inf returned unchanged) andtest_naturaldelta_overflow(finite1e40still raisesOverflowError). Fulltests/test_time.pypasses (387 passed).