[Tutor] Integer?

Kent Johnson kent37 at tds.net
Wed Dec 6 16:46:39 CET 2006


Mike Hansen wrote:
>>> How can I check if a variable is an integer?
>> Luke and John have answered your question, but we should also 
>> ask, why 
>> do you want to do that? Explicit type testing is a code 
>> smell, perhaps 
>> there is a better way to do what you want.
>>
>> Kent
>>
> 
> Kent,
> 
> Can you explain further? Refactoring is in my queue of books to read. In

In general, the preference in Python code is to check for a specific 
behaviour, or just assume the behaviour, rather than to check for a 
specific type. Writing code this way supports duck typing. The two 
approaches are sometimes called Easier to Ask Forgiveness than 
Permission (EAFP) and Look Before You Leap (LBYL).

For example Python has the idea of a file-like object, which is anything 
that behaves like a file. If you have a function that works on a file, 
you could check that the parameter is an actual file. This is an example 
of LBYL:

def doSomething(f):
   if type(f) is not file:
     # error

If you do that, you are preventing your clients from passing a file-like 
object, for example a StringIO object.

On the other hand, if you write doSomething() to just use f as a file, 
any object that has the required methods will just work; an object that 
doesn't have the required methods will raise an AttributeError. That is 
EAFP.

This is just a general guideline, there are certainly cases where 
explicit type checking is appropriate.

> a web app I'm writing, I'm checking the input kind of like this...
> 
> try:
> 	form_value = int(form.getvalue('num_widgets')
> except ValueError:
> 	display_error("Number of Widgets must be a number")

That is fine - you are checking that the string is something that can be 
converted to an int, and catching the error - EAFP. If you tried to 
check the contents of the string before calling int(), that would be LBYL.

Kent



More information about the Tutor mailing list