
str currently has methods like isdecimal, isnumeric and isdigit, but there isn't an isfloat check, which could be very handy. a trivial implementation could be as simple as: try: float(self) return True except ValueError: return False

I agree - the three builtin methods are almost the same (not sure if there is any difference at all), while there is no trivial way to check for a valid float, or otherwise a chosen representation of a decimal number without resorting to a try-except statement, or complicated verification schemes that have to deal with a lot of corner cases. For validity one has to check if there are only digits - and decimal points - and the "-" unary sign. What if there is more of a "." in the string? what if the "-" is not the first character? And besides validity checking, there are also validity choices: What if an unary "+" is present? Whitespace ok? "_" as digit separator ok? scientific exponential notation accepted? What about Inf and Nan literals? What about taking into account the locale setting? But maybe, instead of yet another str method, a "parsefloat" function that could get arguments and sensitive defaults for some choices - it could live in "math" or "numbers". I think it would be preferable than, say, adding a lot of options to the `float` constructor. These are the options I can think of the top of my mind: ```python def parsefloat( input: str, /, *, unary_minus: Bool = True, unary_plus: Bool = False, exponential: Bool = False, inf_literal: Bool = False, nan_literal: Bool = False, whitespace: Bool = False, use_locale: Bool = False, digit_separators: Bool = False, base: int = 10 (?), decimal_places: Optional[int]=None(?), enforce_decimal_places: Bool = False(?), raise_on_error: Bool = False(?), ...) -> Tuple[Bool, float]: ... ``` The return value would consitss of a boolean, where True would indicate success, and then the number. Or it could return a single float, returning a NaN in case of parsing error. this is simple callable - but it could be built on top of a class that could take the configurations and parse more than one number - it would be fit as a float parser to be supplied for tasks like Json decoding, or converting values in a Pandas Series. On Sun, 27 Dec 2020 at 14:12, Tushar Sadhwani <tushar.sadhwani000@gmail.com> wrote:

On Mon, Dec 28, 2020 at 9:22 AM Joao S. O. Bueno <jsbueno@python.org.br> wrote:
I agree - the three builtin methods are almost the same (not sure if there is any difference at all),
Yes - they all check if the string matches a particular set of characters.
If you want to know whether the float() call will throw, the best way to check is to call float() and see if it throws.
How about a built-in called "float", which either returns the floating-point value represented by the string, or signals an invalid string with an exception?
YAGNI. If you want to allow specific subsets of valid options, it's not that hard to do your own validation.
The return value would consitss of a boolean, where True would indicate success, and then the number. Or it could return a single float, returning a NaN in case of parsing error.
Or it could raise in the case of parsing error. That's the Pythonic way. ChrisA

On Sun, 27 Dec 2020 at 19:31, Chris Angelico <rosuav@gmail.com> wrote: try/except is the current usable pattern (it is in the original posting anyway) I tried to make clear this should be in addition to that - But yes, I failed to mention in my message that I think such a function would mostly benefit beginners learning around with "input" and "print" - it is painful to suddenly have to tour the students on several other concepts just to get a correct user-inputed number. (OTOH, yes, for code on this level, one normally won't be concerned if the program user will be typing "1.02e2" on the `input` prompt). The point is exactly that parsing a number correctly, and moreover respecting these options, is subject to error and the stdlib could benefit from a construct that would not require a try/except block for everything. (As you can see, I contemplate that raising may be a desired option for a flexible function, and there is an option for that in my example signature) . ChrisA

On Mon, Dec 28, 2020 at 9:55 AM Joao S. O. Bueno <jsbueno@python.org.br> wrote:
And my point is that try/except is a perfectly usable pattern. You don't need to probe a string to figure out if you'd then be able to convert it to a float - just attempt the conversion.
You can always write the flexibility yourself. Most of the time you won't need anything like that much flexibility. ChrisA

On 2020-12-27 at 19:55:39 -0300, "Joao S. O. Bueno" <jsbueno@python.org.br> wrote:
OTOH, learning that translating a user-entered string to a floating point number is not as simple as it sounds is a great lesson. Please don't teach beginners that handling user input (let alone floating point arithmetic) is easy and/or foolproof. Start with letting the program fail when the input is invalid, teach them to isolate input validation into its own function(s), and introduce try/except as one method of control flow in a validation function.

You should really just write your own function -- Python can't include every validation function you can think of. It already provides an extensible and well tested float conversion which throws an exception on bad input (the 'float' constructor) You want it to not throw an exception, but rather return a status indicating success. This is called Look Before You Leap (LBYL) and is considered un-Pythonic (i.e. is not standard practice while writing Python). If you absolutely must have it in this format (which you shouldn't), you should just write a function that accepts a string, and has a try/except block and then returns the status. Again, don't do this, it's not good practice: def parsefloat(s): try: return float(s) except: return none # or whatever you want to indicate failure I think the confusion of the 'isdigit()' method (and thus your original inquiry into a 'isfloat()' meyhod) stems from a misunderstanding; 'isdigit()' tests whether characters are in a Unicode character set or not -- it doesn't actually convert to a number. Parsing floats is a more complicated and different problem, which doesn't belong in the 'str' class, and already does exist in the 'float' class. Although you say that try/except blocks are ugly/unnecessary/etc, try programming with LBYL idioms as you've suggested. I think you'll find they're not only more verbose, less necessary, and uglier, but they also make exception shadowing much easier (and thus, proper exception handling harder to do). On Sun, Dec 27, 2020, 5:58 PM Joao S. O. Bueno <jsbueno@python.org.br> wrote:

Alright, I see why `str.isfloat()` isn't a thing, and having a builtin float validation function was besides the point anyway. Thanks for the clarifications :)

I agree - the three builtin methods are almost the same (not sure if there is any difference at all), while there is no trivial way to check for a valid float, or otherwise a chosen representation of a decimal number without resorting to a try-except statement, or complicated verification schemes that have to deal with a lot of corner cases. For validity one has to check if there are only digits - and decimal points - and the "-" unary sign. What if there is more of a "." in the string? what if the "-" is not the first character? And besides validity checking, there are also validity choices: What if an unary "+" is present? Whitespace ok? "_" as digit separator ok? scientific exponential notation accepted? What about Inf and Nan literals? What about taking into account the locale setting? But maybe, instead of yet another str method, a "parsefloat" function that could get arguments and sensitive defaults for some choices - it could live in "math" or "numbers". I think it would be preferable than, say, adding a lot of options to the `float` constructor. These are the options I can think of the top of my mind: ```python def parsefloat( input: str, /, *, unary_minus: Bool = True, unary_plus: Bool = False, exponential: Bool = False, inf_literal: Bool = False, nan_literal: Bool = False, whitespace: Bool = False, use_locale: Bool = False, digit_separators: Bool = False, base: int = 10 (?), decimal_places: Optional[int]=None(?), enforce_decimal_places: Bool = False(?), raise_on_error: Bool = False(?), ...) -> Tuple[Bool, float]: ... ``` The return value would consitss of a boolean, where True would indicate success, and then the number. Or it could return a single float, returning a NaN in case of parsing error. this is simple callable - but it could be built on top of a class that could take the configurations and parse more than one number - it would be fit as a float parser to be supplied for tasks like Json decoding, or converting values in a Pandas Series. On Sun, 27 Dec 2020 at 14:12, Tushar Sadhwani <tushar.sadhwani000@gmail.com> wrote:

On Mon, Dec 28, 2020 at 9:22 AM Joao S. O. Bueno <jsbueno@python.org.br> wrote:
I agree - the three builtin methods are almost the same (not sure if there is any difference at all),
Yes - they all check if the string matches a particular set of characters.
If you want to know whether the float() call will throw, the best way to check is to call float() and see if it throws.
How about a built-in called "float", which either returns the floating-point value represented by the string, or signals an invalid string with an exception?
YAGNI. If you want to allow specific subsets of valid options, it's not that hard to do your own validation.
The return value would consitss of a boolean, where True would indicate success, and then the number. Or it could return a single float, returning a NaN in case of parsing error.
Or it could raise in the case of parsing error. That's the Pythonic way. ChrisA

On Sun, 27 Dec 2020 at 19:31, Chris Angelico <rosuav@gmail.com> wrote: try/except is the current usable pattern (it is in the original posting anyway) I tried to make clear this should be in addition to that - But yes, I failed to mention in my message that I think such a function would mostly benefit beginners learning around with "input" and "print" - it is painful to suddenly have to tour the students on several other concepts just to get a correct user-inputed number. (OTOH, yes, for code on this level, one normally won't be concerned if the program user will be typing "1.02e2" on the `input` prompt). The point is exactly that parsing a number correctly, and moreover respecting these options, is subject to error and the stdlib could benefit from a construct that would not require a try/except block for everything. (As you can see, I contemplate that raising may be a desired option for a flexible function, and there is an option for that in my example signature) . ChrisA

On Mon, Dec 28, 2020 at 9:55 AM Joao S. O. Bueno <jsbueno@python.org.br> wrote:
And my point is that try/except is a perfectly usable pattern. You don't need to probe a string to figure out if you'd then be able to convert it to a float - just attempt the conversion.
You can always write the flexibility yourself. Most of the time you won't need anything like that much flexibility. ChrisA

On 2020-12-27 at 19:55:39 -0300, "Joao S. O. Bueno" <jsbueno@python.org.br> wrote:
OTOH, learning that translating a user-entered string to a floating point number is not as simple as it sounds is a great lesson. Please don't teach beginners that handling user input (let alone floating point arithmetic) is easy and/or foolproof. Start with letting the program fail when the input is invalid, teach them to isolate input validation into its own function(s), and introduce try/except as one method of control flow in a validation function.

You should really just write your own function -- Python can't include every validation function you can think of. It already provides an extensible and well tested float conversion which throws an exception on bad input (the 'float' constructor) You want it to not throw an exception, but rather return a status indicating success. This is called Look Before You Leap (LBYL) and is considered un-Pythonic (i.e. is not standard practice while writing Python). If you absolutely must have it in this format (which you shouldn't), you should just write a function that accepts a string, and has a try/except block and then returns the status. Again, don't do this, it's not good practice: def parsefloat(s): try: return float(s) except: return none # or whatever you want to indicate failure I think the confusion of the 'isdigit()' method (and thus your original inquiry into a 'isfloat()' meyhod) stems from a misunderstanding; 'isdigit()' tests whether characters are in a Unicode character set or not -- it doesn't actually convert to a number. Parsing floats is a more complicated and different problem, which doesn't belong in the 'str' class, and already does exist in the 'float' class. Although you say that try/except blocks are ugly/unnecessary/etc, try programming with LBYL idioms as you've suggested. I think you'll find they're not only more verbose, less necessary, and uglier, but they also make exception shadowing much easier (and thus, proper exception handling harder to do). On Sun, Dec 27, 2020, 5:58 PM Joao S. O. Bueno <jsbueno@python.org.br> wrote:

Alright, I see why `str.isfloat()` isn't a thing, and having a builtin float validation function was besides the point anyway. Thanks for the clarifications :)
participants (5)
-
2QdxY4RzWzUUiLuE@potatochowder.com
-
Cade Brown
-
Chris Angelico
-
Joao S. O. Bueno
-
Tushar Sadhwani