I don't know how common it is to want to distinguish between string
representations of integers and those of floats. It seems like a function that
could have a million little variations: What if my boss says that now my input
integers can have commas? Or have extra space added? Or if integer-valued
floats should be considered integers? What if we run into localization issues
with a commas-versus-periods-as-decimal-separator? What if we want to start
accepting fractions like "22/7"? What if we find dollar signs in front? What if
we want to return 0 or NaN in place of None?
It seems to me that with all of these possible variations, it's best to spell
out in your code exactly what to do for your individual use case, using
try/except as necessary. That's not to say that you shouldn't make this
function in your own code -- maybe you're personally writing dozens of scripts
that use exactly this function. If so, great: add it to a personal utility
library and import it when you need it. But I'm not sure it's worth the bloat
of giving that same function to all Python users across the world whether they
want it or not.
By the way, if I were implementing something like this, I would probably
instead write something like
def parse_value(string):
try:
return int(string)
except ValueError:
pass
try:
return float(string)
except ValueError:
return None
so that all of the parsing is together, and then elsewhere in the code write
isinstance(number, float) rather than passing strings around and repeatedly
parsing/re-parsing with some kind of isfloat(string) operation.
_______________________________________________
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/CVMAIKDQMHQSOA7IIG75TNA5TBXGW3UD/
Code of Conduct: http://python.org/psf/codeofconduct/