On Sat, Oct 02, 2021 at 02:17:32AM -0000, Debashish Palit wrote:
> The method need not take care of every variation. Currently there is
> no method to check for a float in a string even without formatting.
Right, because no method is needed. If you want to convert something to
a float (whether a string, or anything else), it is nearly always
better to try to convert it:
try:
result = float(s)
except TypeError:
# Cannot be converted to a float.
... # some fallback routine
This software pattern is called "Easier to Ask Forgiveness than
Permission" and is usually more efficient and safer than the opposite
pattern, "Look Before You Leap".
https://devblogs.microsoft.com/python/idiomatic-python-eafp-versus-lbyl/
So the number of use-cases for your function are probably very few.
> 1. When accepting user input with the input() function, you may get
> integers and not floats. If you just convert the strings to floats,
> you will get the result of a calculation as a float. Here the type of
> the input needs to be preserved.
Can you give a real example of a case where you are doing calculations
on a number provided as a string, but need to preserve the original
format?
> 2. A case that may come up often is passing numbers as strings to an
> instance method.
Why pass your numbers to functions as *strings* if you want to do
calculations with them?
> After converting the number to a float, you may want
> to output the value in a repr method. Saving the precise type would
> help.
If you need to preserve the exact input for the repr method, you should
preserve the actual input.
class MyClass:
def __init__(self, astring):
self._arg = astring
self.number = float(astring)
def __repr__(self):
return 'MyClass(%s)' % self._arg
> The parse_value function would work as well but str.isfloat is more
> inline with the current string methods.
Not really. There are no string methods to test for:
- ints
- floats
- complex numbers
- fractions
- decimals
you are expected to just try to convert and catch the exception if it
occurs (EAFP). So this would be new.
The existing string methods isdecimal, isdigit and isnumeric test for
Unicode categories, for example:
'\N{CIRCLED DIGIT THREE}'.isdigit()
--> returns True
'\N{CIRCLED DIGIT THREE}'.isdecimal()
--> returns False
'\N{ETHIOPIC NUMBER FIFTY}'.isnumeric()
--> returns True
'\N{ETHIOPIC NUMBER FIFTY}'.isdigit()
--> returns False
--
Steve
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/SXXV5YPEB6QBPNZ5PQ3E4O7GI4XRMFE4/
Code of Conduct: http://python.org/psf/codeofconduct/