New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
math.isfinite() can raise exception when called on a number #91277
Comments
>>> help(math.isfinite)
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.So, one would expect the following expression to return >>> math.isfinite(10**1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float(There likewise is a corresponding issue with other, similar, functions). This especially hurts since PEP-484 states that having a Sequence[float] Now, strictly speaking, DESCRIPTION ...but according to "man 3 isfinite", the math.h "isfinite" is a macro and not a function - and the man page does not show type information for that reason. |
|
The math.isfinite() docs could be changed to something like, "coerces x to a float if possible and then returns True if x is neither an infinity nor a NaN, and False otherwise." Or there could be a general note about which functions (most of them) coerce to float (which can fail). With respect to typing and PEP-484, I don't see a bug or documentation issue. Types relationships are useful for verifying which methods are available, but they don't make promises about the range of valid values. For example math.sqrt(float) -> float promises which types are acceptable but doesn't promise that negative inputs won't raise an exception. Likewise, "n: int=10; len(range(n))" is type correct but will raise an OverflowError for "n = 10**100". |
|
The problem with PEP-484 is that if one wants to use static type analysis, neither of these options are good:
def foo(x: float) -> float:
"""Foos the barbazArgs: The floats in the docstring give me a guarantee: "If I feed in a float, I am guaranteed to receive back a float". The floats in the static type annotation merely say "yeah, can be float or int, and I'd call it ok in these cases" - that's a very different statement.
With respect to this latter option, I think we can wait for "losing the ability to stringently reason about the behavior of code" to cause major security headaches. That's basically opening up the door to many problems at the level of "I can crash the webserver by requesting the url http://lpt1". |
|
Most (but not all) functions in the math module implicitly convert its arguments to float. Here we can get an OverflowError. Do we want to add a note to every function that does it? Or add a general note at the top of the file and add exclusion notes to functions which do not convert arguments to float? BTW, there is a general note: "Except when explicitly |
|
Isn't this just a quality of implementation issue? math.isfinite should return True for all ints, since all ints are finite. (There are no int infinities or NANs). There is no need to coerce them to float to know that they are finite. Likewise for Fractions. If they overflow, that could be caught and True returned. Decimal infinities convert to float infinities, so the only way you can get an overflow error is if the Decimal is finite but too big to convert. So again, isfinite could (should?) catch the overflow error and return True. Any numeric type that has an infinity which does not coerce to float infinity, but overflows instead, is buggy, and its not isfinite's responsibility to protect against that. So here is my suggestion: isfinite() should return True for all ints, without needing to coerce them to float. For other numeric types, it should try to coerce them to float, and catch OverflowError and raise True. This should be documented, so that other numeric types know what contract they are required to follow (infinity coerces to float infinity). I'm going to change this to an enhancement for 3.11 (or 3.12). |
Whoa there. You're venturing into changing what those math functions were all about and the core approach to how they operate. A zigzag to this new direction would need discussion with all the math folks. Many tools in the math module are thin wrapper around libmath and we never intended to be universal handlers of all numeric types. We have a lot of functions that start by coercing their input to a float. My two cents is that this would open an endless can of worms and make everyone pay a time and complexity cost for a feature that almost no one needs. AFAICT is more of a purity issue than an actual practical need that would warrant separate code paths (for example, we recently closed an issue where someone wanted math.log() to have a separate code path for Fraction inputs where it return log(f.numerator) - log(f.denominator) with the goal of handling fractional values smaller than float_min). |
|
I'll testify that I won't volunteer one second of my time pursuing these abstract "purity" crusades ;-) If was had to cater to all possible "numberish" types, we'd never add anything new again :-( Doing that in a principled way requires dedicated new dunder methods, and that's a high bar. That I said, I extended math.log() decades ago to work on giant integers. It was useful for real projects I was working on at the time - I was scratching my own itches. |
|
Tim, the problem may well be simply due to the documentation of math.isfinite() being off here. This is what we currently have: https://docs.python.org/3/library/math.html#math.isfinite === math.isfinite(x)
Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.)New in version 3.2. If this were re-worded as follows (and corresponding changes were made to other such functions), everyone would know what the expectations and behavior are: === math.isfinite(x)If New in version 3.2. This would be an accurate defining description of the actual behavior. Note that, "thanks to PEP-484", this abbreviation would currently be ambiguous though: === math.isfinite(x)If New in version 3.2. ("ambiguous" since "float" means different things as a static type and as a numbers class - and it is not clear what would be referred to here). Changing/generalizing the behavior might potentially be an interesting other proposal, but I would argue that then one would want to change the behavior of quite a few other functions here as well, and all this should then perhaps go into some other However, since the Python philosophy is to not rely on bureaucracy to enforce contracts (as C++, Java, etc. do it), but instead to rely on people's ability to define their own contracts, making the math.isfinite() contract more accurate w.r.t. actual behavior in the CPython implementation via extra clarification looks like a good thing to do, no? |
I came to this enhancement request wanting to contribute support for it, but these kinds of statements are the obstacle over which I'm currently stumbling. I want it to be the case that given the
Well, yeah. This issue definitely makes me wonder if that discussion would be worth having, and curious to what extent it may have been had before. (I wonder if you meant "the math folks" or "the
Agreed - but I'd hypothesize that "people working with floats" is likely only a subset of those who would add
Agreed, and I suspect there's an opportunity here to let the perfect be the enemy of the good, and we oughtn't take advantage of that opportunity. I'd like to advocate that the |
|
A reasonable expectation is that if There are also technical problems. The only general way of supporting arbitrary numbers in |
|
I concur with Tim that this is just an abstract purity nit and also with Serhiy that this doesn't make sense in light of how the other functions work. I'll add that I don't see that any real user issue is being addresses here. Mostly, this seems to be an "it bugs me" request rather than a "people need this" request. Thanks for the suggestion, but we will decline. |
|
Right now, the === Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.) New in version 3.2.Current behavior does not align with the documentation. This is by definition a bug. There are multiple options for resolving this, one of them is keeping the current behavior and adjusting the documentation. |
|
Does it return True for an infinity or a NaN? Does it return False for any x which is neither an infinity nor a NaN? |
|
Does it show any behavior other than returning True or False on type-wise valid numerical input? Yes. |
|
Perhaps I need to explain this more slowly. https://docs.python.org/3/library/math.html#math.isfinite clearly says: The opposite of "Responds with True on X" is not "Responds with False on X", but "Fails to respond with True on X". So, in small steps:
Is 10**1000 a real number? Pretty much so. PEP-484 even thinks this is a "float"(!) So, does math.isfinite() violate its own documentation? How can there be even a discussion about that? There is of course some sort-of open issue around "what is valid input here"? "These functions cannot be used with complex numbers." This is a clear case of "exceptio probat regulam in casibus non exceptis" - the "complex numbers" are here mentioned as an exception to the not explicitly stated rule that these functions can process not-complex, i.e. real, input. |


Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: