(Jul-09-2018, 10:18 PM)micseydel Wrote: @Skaperen, what exactly do you mean by "determine if an object passed in to a function is a number"? It sounds like you already have a Python object, so you're not dealing with a user-input string.
Python is not only dynamically typed (by design) but also duck typed (by convention), so yes as you say the "Pythonic" thing to do would be to try to use it and then catch an exception if you're really concerned about an operation not being supported, but in practice we usually don't bother looking for an exception. Usually we wouldn't have an is_number function like you're describing, even.
it might actually be a user input string. so i am putting conversions under the try clause, too. i'm not really concerned what is under try may well just be the start of how the number will be used. i just want to include enough meaning in the message (in the raised exception) to help the end user in lieu of the programmer since some errors may well just be a user error.
of course the programmer should understand the traceback and correct errors ... if it is an error in the code. but the end user who knows nothing about coding, can make mistakes, too, such as typing a comma instead of a period in a number (perhaps because they are in Europe and it's a habit). whatever it is, if i am the programmer, i want to tell users about their errors .. or where i am making tools for programmers, make it easy for them to inform their users.
what if you have a program for farmers to type in how many acres they need seed for and this one farmer types in: 1,649.5
do you want to say to him ... ValueError: could not convert string to float: '1,649.5'
or maybe ... decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
i wouldn't. at they very least i'd want to say ... the number of acres is not a valid number. or i could do better and tell him not to type those commas. or maybe i could just take it that way.
when some web shop wants CC numbers without the spaces, i just want to tell them "how ****ing hard is it to delete spaces in the code" or maybe just "cc=cc.replace(' ','') # how hard is that?".
yeah, if "a number" to the code i'm writing could be a decimal string and/or a complex number, the the test needs to include that. but what if the next project would screw up bad with a complex number and some user types one in. it needs different code. gotta define what you want. do you want to allow the switched use of commas and periods? is "1,2" a number?