trapping errors in function call syntax
Duncan Booth
duncan.booth at invalid.invalid
Mon Feb 13 16:25:34 EST 2006
Fredrik Lundh wrote:
> Avi Kak wrote:
>> Suppose I write a function that I want to be called
>> with ONLY keyword argumnts, how do I raise an
>> exception should the function get called with
>> what look like position-specfic arguments?
>
> here's one way to do it:
>
>>>> def func(*args, **kw):
> ... def myrealfunc(a=1, b=2, c=3):
> ... print a, b, c
> ... if args:
> ... raise TypeError("invalid call")
> ... return myrealfunc(**kw)
> ...
>
If you aren't particular about the message then you can do without the args
argument and just define it with **kw:
>>> def func(**kw):
def myrealfunc(a=1, b=2, c=3):
print a, b, c
return myrealfunc(**kw)
>>> func(1)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in -toplevel-
func(1)
TypeError: func() takes exactly 0 arguments (1 given)
>>> func(a=3)
3 2 3
>>>
and if you are particular about the message perhaps submitting a patch to
generate a more appropriate message would be a good idea.
More information about the Python-list
mailing list