I have not tried decorators yet or functions within functions, but this current un-pythonic method seems a little convoluted. I don't like how I need to repeat myself when I check the return_type
3 times.
Any suggestions are welcome, especially if the repetion can be dealt with in an elegant way. Please note that I am not that interested in the numerous reference to test if an object is a number as I believe this part is incorporated within my solution. I am interested in addressing the 3x duplication to deal with the return type. Moreover, while I appreciate the locale method is the more rigorous way of dealing with internationalisation, I prefer the simplicity of allowing the caller more flexibility in choosing the characters.
Also, some people on Stack Overflow just posted trivial solutions to the smaller boolean is_number
function that has been asked many times.
def is_number(obj, thousand_sep=',', decimal_sep=None, return_type='b'):
""" determines if obj is numeric.
if return_type = b, returns a boolean True/False
otherwise, it returns the numeric value
Examples
--------
>>> is_number(3)
True
>>> is_number('-4.1728')
True
>>> is_number('-4.1728', return_type='n')
-4.1728
>>> is_number(-5.43)
True
>>> is_number("20,000.43")
True
>>> is_number("20.000,43", decimal_sep=",", thousand_sep=",")
True
>>> is_number("20.000,43", decimal_sep=",", thousand_sep=".", return_type="n")
20000.43
>>> is_number('Four')
False
>>> is_number('Four', return_type='n')
"""
try:
if is_string(obj):
if decimal_sep is None:
value = float(obj.replace(thousand_sep, ""))
else:
value = float(obj.replace(thousand_sep, "").replace(decimal_sep, "."))
if return_type.lower() == 'b':
return True
else:
return value
else:
value = float(obj)
if return_type.lower() == 'b':
return True
else:
return value
except ValueError:
return False
if return_type.lower() == 'b':
return False
else:
return None