what a cheap rule

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Nov 25 20:10:09 EST 2010


On Thu, 25 Nov 2010 08:15:21 -0800, Yingjie Lan wrote:

> Intuition #1: as if you raise an exception type, and then match that
> type.
> It seems that no instances
> are involved here (Intuitively).

Your intuition is not my intuition, nor does it match what Python 
actually does. You can only go so far on *guessing* what a programming 
statement does, sometimes you need to actually read the Fine Manual.


> See an example code here:
> 
> try: raise KeyError
> except KeyError: pass

As the documentation states, this creates an instance of KeyError. 

    raise evaluates the first expression as the exception object. 
    It must be either a subclass or an instance of BaseException. 
    If it is a class, the exception instance will be obtained when 
    needed by instantiating the class with no arguments.

http://docs.python.org/py3k/reference/simple_stmts.html#the-raise-statement

So there is no semantic difference between "raise KeyError" and 
"raise KeyError()". Why should there be? What practical difference would 
you expect?


If you do this:

try: raise KeyError
except KeyError as ke: print(ke)

you will see that the value caught is an instance, not the class.


 
> Intuition #2: you raise an exception
> instance, and then match an instance by its type. See an example code
> here:
> 
> try: raise KeyError()
> except KeyError as ke: pass


Your intuition is wrong. Exceptions aren't matched by type, they are 
*always* matched by an isinstance() check, and that includes subclasses.


>>> try: raise KeyError  # with or without parentheses makes no difference
... except Exception as e: print(type(e))
...
<class 'KeyError'>


> Those two comprehensions are not compatible, and thus the one that
> promotes correct understanding should be encouraged,
> while the other should be discouraged, and maybe even be made iliegal.

You seem to have misunderstood both forms of the raise statement. Should 
we make exceptions illegal because you can't correctly guess what they do?



-- 
Steven



More information about the Python-list mailing list