Checking function calls

Joel Hedlund joel.hedlund at gmail.com
Wed Mar 8 18:00:16 CET 2006


If you have access to the source of the function you want to call (and know what kind of data types it wants in its args) you can raise something else for bad parameters, eg:

----------------------------------------------------------------
class ArgTypeError(TypeError):
    def __init__(self, arg):
        self.arg = arg

    def __str__(self):
        return "bad type for argument %r" % self.arg

def moo(cow):
    if not isinstance(cow, str):
        raise ArgTypeError('cow')
    print "%s says moo!" % cow
    # this error is not caused by wrong arg type:
    var = 1 + 's'

function = moo

for arg in [1, 'rose']:
    try:
        function(arg)
    except ArgTypeError, e:
        print e
----------------------------------------------------------------

Output:
----------------------------------------------------------------
bad type for argument 'cow'
rose says moo!

Traceback (most recent call last):
  File "/merlot1/yohell/eraseme/test.py", line 23, in -toplevel-
    make_noise('rose')
  File "/merlot1/yohell/eraseme/test.py", line 13, in moo
    raise TypeError
TypeError
----------------------------------------------------------------
    
Hope it helps
/Joel Hedlund



More information about the Python-list mailing list