[Tutor] recursive problem

Steven D'Aprano steve at pearwood.info
Sat Sep 11 20:03:43 CEST 2010

On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:

> But why is type checking then wrong.
> Lets says I want a module who must work on strings, tuple and lists.

It's not *always* wrong, but let me ask you... why do you want to 
*limit* the function to work on ONLY strings, tuples and lists?

The Python philosophy is "duck typing" -- if it walks like a duck, and 
swims like a duck, it is close enough to a duck that we don't care that 
it's not actually a duck, but a goose.

Here's an example:

def f1(x):
    if type(x) is int or type(x) is float:
        print("x + 1 = %s" % (x+1))
        print("x is not a number")

def f2(x):
        print("x + 1 = %s" % (x+1))
    except (ValueError, TypeError):
        print("x is not a number")

>>> f1(3)
x + 1 = 4
>>> from decimal import Decimal
>>> f1(Decimal(3))
x is not a number
>>> f2(Decimal(3))
x + 1 = 4

Function f1 makes the assumption that only ints and floats can be added, 
and so it gives the wrong results with Decimal numbers. But function f2 
uses "duck typing" -- it doesn't care what sort of number x is, only 
that it can be added.

> Can I then use EAFP ?
> Without type checking I never know which one is used now.

Going back to type-checking... sometimes you can't avoid it. Sometimes 
you use it because it is easier, and you don't care enough to write 
more complicated code. Sometimes you really do care what the type is:

>>> "abc"[2.0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

Steven D'Aprano

More information about the Tutor mailing list