trapping errors in function call syntax

Andrew Gwozdziewycz apgwoz at gmail.com
Mon Feb 13 14:28:45 EST 2006


While we're at it... Can someone point me to either an old post, or
documentation about tuple expansion with * ? I recently saw it used
and was shocked as i had no clue what it really did. I didn't know it
could be used outside of function definitions.

On 2/13/06, Fredrik Lundh <fredrik at pythonware.com> 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)
> ...
> >>> 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>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--
Andrew Gwozdziewycz <apgwoz at gmail.com>
http://ihadagreatview.org
http://plasticandroid.org



More information about the Python-list mailing list