[Baypiggies] Type checking - argument for it being bad practice?

Keith Dart keith at dartworks.biz
Fri Oct 8 06:49:52 CEST 2010

=== On Thu, 10/07, Seth Friedman wrote: ===
> Is something like
> assert(isinstance(inputNumber,isActuallyANumberWeExpected)) really
> that cumbersome, aside from my long variable names?  

I don't see that as any better than just using it directly. In the
assert case you may get an AssertError thrown that you will have to
catch somewhere. But if you just apply the operator you get a TypeError
thrown that you have to catch somewhere. I think Python is a
"optimistic" language. You just go and do it and catch errors if they

An alternative is to "cast" it. if you really don't know what you're
getting, just use something like "int(inputNumber) + 1" which works as
long as the input can be converted. I think that's related to the "duck
typing" that is pervasive in Python.

> I mean, what's wrong with code asserting that what it got passed was
> what was expected?  If there's blind faith that stuff will just work
> beneath the scenes, ok, but when i *know* it won't, why not fail
> there, and explicitly? 

It will fail anyway, and explicitly, with a TypeError. Python is already
doing the type checking "under the hood", so you don't have to add that
extra layer.

> If I write a function that can be called from
> python code or command line, I might get a string of a number or an
> int, and I will probably forget 6 months from now what I wrote the
> code to handle, without some kind of prompt.  The closer that prompt
> is to the disconnect, the better.

Right, so just do input validation up front. e.g. 

  x = int(argv[1])
except (TypeError, ValueError, IndexError):
	print "You must supply an int."

From then on you know it's an int, no reason to double-check with an
assert later.

As for remembering what the function accepts, that's what doc strings
are for. ;-)

But an assert can't hurt, if you really want, for developing new code.
You can later run Python in optimized mode (-OO flag), and the asserts
are removed from the bytecode. But if you run in optimized mode and do
get a bad value you will in this case get the TypeError and not the
AssertError that you previously got. So the behavior will change
between the two modes.

 -- Keith Dart

-- ------------------------------
Keith Dart

More information about the Baypiggies mailing list