Where to put the error handing test?

Paul Miller paul.w.miller.please.dont.spam.me at wmich.edu
Tue Nov 24 04:31:28 EST 2009


On Mon, 23 Nov 2009 22:27:24 -0800, alex23 wrote:

> As a very rough example:
> 
>     def g(x):
>         try:
>             assert isinstance(x, int)
>         except AssertionError:
>             raise TypeError, "excepted int, got %s" % type(x)
>         # ... function code goes here
> 
>     def f(x):
>         try:
>             g(x)
>         except TypeError:
>             # handle the problem here
>         # ... function code goes here

I know you say this is a "very rough" example, but, generally you don't 
want to do this kind of "type checking" with isinstance.  Rather, it's 
better to just simply manipulate x as if it were an integer and rely on 
Python to check to see if x supports the operations you're trying to do 
with it.  For instance, say we have

def g(x):
    return x * x

def f(x):
    return g(x) + 2

If you try to pass any value to either of these functions that doesn't 
support the required operations, Python itself will complain with a 
TypeError.  Since the interpreter needs to do this check *anyway*, 
there's no real sense in repeating it manually by checking isinstance.




More information about the Python-list mailing list