trapping errors in function call syntax

Tim Hochberg tim.hochberg at ieee.org
Mon Feb 13 14:28:51 EST 2006


Avi Kak wrote:
> Hello:
> 
>    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?
> 
>   Any help would be appreciated.

Say you want the signature to be foo(a, b, c) with no positional 
arguments allowed. You can do this:

def foo(*args, **kwargs):
     a = kwargs.pop('a')
     b = kwargs.pop('b')
     c = kwargs.pop('c')
     if args or kwargs:
         raise TypeError("foo takes only keyword arguments: foo(a,b,c)")
     # ...


Or something similar.

-tim




More information about the Python-list mailing list