trapping errors in function call syntax

Fredrik Lundh fredrik at pythonware.com
Mon Feb 13 14:22:49 EST 2006


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)
...
>>> func(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 5, in func
TypeError: invalid call
>>> func(a=3)
3 2 3
>>> func()
1 2 3

here's another one:

>>> def func(dummy=None, a=1, b=2, c=3):
...     if dummy is not None:
...             raise TypeError("invalid call")
...     print a, b, c

(but this is easier to trick).

hope this helps!

</F>






More information about the Python-list mailing list