Newbie: static typing?

Chris Angelico rosuav at gmail.com
Tue Aug 6 05:29:40 EDT 2013


On Tue, Aug 6, 2013 at 10:01 AM, Rui Maciel <rui.maciel at gmail.com> wrote:
> It would be nice if some functions threw an error if they were passed a type
> they don't support or weren't designed to handle.  That would avoid having
> to deal with some bugs which otherwise would never happen.
>
> To avoid this sort of error, I've been testing arguments passed to some
> functions based on their type, and raising TypeError when necessariy, but
> surely there must be a better, more pythonic way to handle this issue.

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:

>>> add_three_values(1,"foo",[4,6])
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    add_three_values(1,"foo",[4,6])
  File "<pyshell#25>", line 2, in add_three_values
    return x+y+z
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The Pythonic way is to not care what the objects' types are, but to
simply use them.

In C++ and Java, it's usually assumed that the person writing a
function/class is different from the person writing the code that uses
it, and that each needs to be protected from each other. In Python,
it's assumed that either you're writing both halves yourself, or at
least you're happy to be aware of the implementation on the other
side. It saves a HUGE amount of trouble; for instance, abolishing
private members makes everything easier. This philosophical difference
does take some getting used to, but is so freeing. The worst it can do
is give you a longer traceback when a problem is discovered deep in
the call tree, and if your call stack takes more than a page to
display, that's code smell for another reason. (I've seen Ruby
tracebacks that are like that. I guess Ruby programmers get used to
locating the important part.)

ChrisA



More information about the Python-list mailing list