On Thu, 30 Aug 2012, Steven D'Aprano wrote:

On 28/08/12 21:24, Wayne Werner wrote:
On Mon, 27 Aug 2012, Richard D. Moores wrote:

What the best way to test if something's an integer?

try:
    whatever_you_want(supposed_integer)
except ValueError:
    print("Oops, that wasn't an integer! Please try again")

That's usually the best way...

Actually, that's close to the worst way, since you take a nice, useful
exception which prints a traceback showing exactly what went wrong, and
replace it with a pointless, silly message which can't be caught by the
caller.

Trying again may be impossible, or inappropriate, and certainly isn't
up to the function to make that decision, that's up to the caller to
decide what is the appropriate response to invalid data.

I suppose I should've replaced the print() call with

    # Whatever recovery/handling code you need here

My intention was to remove the bit about checking for an integer away from the spot that was checking it, out into an exception handler where it belongs.

I was also under the (mistaken?) impression that the use case was an interactive type call, and used something like:

    supposed_integer = raw_input("Please enter an integer: ")

    # exception handling here



But yes, if you're writing code that is meant to be called by someone else then that code is horrible, and exactly the wrong pattern to follow.

-Wayne
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to