polymorphism w/out signatures?

Roy Smith roy at panix.com
Mon May 10 14:12:12 EDT 2004


Peter Hansen <peter at engcorp.com> wrote:
> Or is there some way that the following code can
> possibly fail with a TypeError, for any reason
> whatsoever?
> 
>    someName = [someName]

It's a bit contrived (and also not exactly what you asked for), but 
consider something like:

class foo:
    def __getattr__ (self, name):
        return 1 + ""

    def barf (self):
        self.someName = [self.someName]

f = foo ()
f.barf ()

which produces this when you run it:

Roy-Smiths-Computer:tmp$ ./try.py 
Traceback (most recent call last):
  File "./try.py", line 11, in ?
    f.barf ()
  File "./try.py", line 8, in barf
    self.someName = [self.someName]
  File "./try.py", line 5, in __getattr__
    return 1 + ""
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The general point is that when catching exceptions, it's usually best to 
include as little code in the try block as you can, to make sure you're 
catching the exception you think you are.  Especially in a highly 
dynamic language like Python, it's sometimes difficult to think of all 
the possible ways code can fail.

Was it Knuth who said, "I've only proven that my program is correct, I 
havn't actually tested it"?  Or was that Dijkstra?



More information about the Python-list mailing list