Newbie: static typing?

Chris Angelico rosuav at gmail.com
Tue Aug 6 06:50:38 EDT 2013


On Tue, Aug 6, 2013 at 11:28 AM, Rui Maciel <rui.maciel at gmail.com> wrote:
> Chris Angelico wrote:
>> def add_three_values(x,y,z):
>>     return x+y+z
>>
>> Do you want to test these values for compatibility? Remember, you
>> could take a mixture of types, as most of the numeric types can safely
>> be added. You can also add strings, or lists, but you can't mix them.
>> And look! It already raises TypeError if it's given something
>> unsuitable:
>
> If the type problems aren't caught right away when the invalid types are
> passed to a function then the problem may only manifest itself in some far
> away point in the code, making this bug needlessly harder to spot and fix,
> and making the whole ordeal needlessly too time consuming.

There are two problems that can result from not checking:

1) The traceback will be deeper and may be less clear.

2) Some code will be executed and then an exception thrown.

If #2 is a problem, then you write checks in. (But be aware that
exceptions can be thrown from all sorts of places. It's usually better
to write your code to cope with exceptions than to write it to check
its args.) But that's a highly unusual case. With >99% of Python
scripts, it won't matter; programming errors are corrected by editing
the source and rerunning the program from the top. (There ARE
exceptions to this, but in Python they're relatively rare. In some of
my serverside programming (usually in Pike), I have to code in *much*
better protection than this. But if you're doing that sort of thing,
you'll know.)

So the real problem here is that, when there's a bug, the traceback is
longer and perhaps unclear. This is at times a problem, but it's not
as big a problem as the maintenance burden of all those extra type
checks. You might have a bug that takes you an extra few minutes to
diagnose because it's actually caused half way up the call stack (or,
worse, it doesn't come up in testing at all and it slips through into
production), but you save hours and hours of fiddling with the type
checks, and perhaps outright fighting them when you want to do
something more unusual. Or you write six versions of a function, with
different type checking. Any of these scenarios is, in my opinion, far
worse than the occasional bit of extra debugging work.

Like everything, it's a tradeoff. And if your function signatures are
sufficiently simple, you won't often get the args wrong anyway.

ChrisA



More information about the Python-list mailing list