trapping errors in function call syntax

Discussion in 'Python' started by Avi Kak, Feb 13, 2006.

  1. Avi Kak

    Avi Kak Guest

    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.

    Avi Kak
     
    Avi Kak, Feb 13, 2006
    #1
    1. Advertisements

  2. Something like this should do the trick:

    def f(*args, **kwargs):
    if args: raise TypeError, "Please use keyword arguments."
    ...

    -Carsten
     
    Carsten Haese, Feb 13, 2006
    #2
    1. Advertisements

  3. here's one way to do it:
    .... def myrealfunc(a=1, b=2, c=3):
    .... print a, b, c
    .... if args:
    .... raise TypeError("invalid call")
    .... return myrealfunc(**kw)
    ....Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    1 2 3

    here's another one:
    .... if dummy is not None:
    .... raise TypeError("invalid call")
    .... print a, b, c

    (but this is easier to trick).

    hope this helps!

    </F>
     
    Fredrik Lundh, Feb 13, 2006
    #3
  4. 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.
     
    Andrew Gwozdziewycz, Feb 13, 2006
    #4
  5. Avi Kak

    Tim Hochberg Guest

    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
     
    Tim Hochberg, Feb 13, 2006
    #5
  6. the reference page is here:

    http://docs.python.org/ref/calls.html

    </F>
     
    Fredrik Lundh, Feb 13, 2006
    #6
  7. Avi Kak

    Duncan Booth Guest

    If you aren't particular about the message then you can do without the args
    argument and just define it with **kw:
    def myrealfunc(a=1, b=2, c=3):
    print a, b, c
    return myrealfunc(**kw)


    Traceback (most recent call last):
    File "<pyshell#14>", line 1, in -toplevel-
    func(1)
    TypeError: func() takes exactly 0 arguments (1 given)
    and if you are particular about the message perhaps submitting a patch to
    generate a more appropriate message would be a good idea.
     
    Duncan Booth, Feb 13, 2006
    #7
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.