Oddity with function default arguments

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sheila King

    Oddity with function default arguments

    Here is something that surprised me tonight:
    [color=blue][color=green][color=darkred]
    >>> def myfunc(x, y, a='A', *mylist):[/color][/color][/color]
    print x
    print y
    print a
    for item in mylist:
    print item

    [color=blue][color=green][color=darkred]
    >>> myfunc(2, 5, 6, 7, 8)[/color][/color][/color]
    2
    5
    6
    7
    8[color=blue][color=green][color=darkred]
    >>> myfunc(1, 2)[/color][/color][/color]
    1
    2
    A[color=blue][color=green][color=darkred]
    >>> myfunc(1, 2, 3, 4, 5)[/color][/color][/color]
    1
    2
    3
    4
    5[color=blue][color=green][color=darkred]
    >>> def myfunc(x, y, *mylist, a='A'):[/color][/color][/color]

    SyntaxError: invalid syntax

    Why isn't the default value for a printing out when I include list
    arguments?

    (This is Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on
    win32, if that makes a difference.)

    I would suspect at first a Python bug, but maybe I'm just not "seeing"
    something that I should?

    --
    Sheila King


  • Erik Max Francis

    #2
    Re: Oddity with function default arguments

    Sheila King wrote:
    [color=blue]
    > SyntaxError: invalid syntax
    >
    > Why isn't the default value for a printing out when I include list
    > arguments?[/color]

    The remaining arguments (*) or remaining keyword arguments (**) go at
    the end of the argument list.

    --
    __ Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
    / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
    \__/ Did you ever love somebody / Did you ever really care
    -- Cassandra Wilson

    Comment

    • Heiko Wundram

      #3
      Re: Oddity with function default arguments

      Am Samstag, 12. Juni 2004 09:05 schrieb Sheila King:[color=blue]
      > Why isn't the default value for a printing out when I include list
      > arguments?[/color]

      You don't include list arguments. You just put positional arguments into a
      function call, and of course a positional argument at the position of the
      argument which has a default declared gets inserted there, that's why you
      don't see the A when you pass more than two arguments.

      All remaining positional arguments (once the named positional arguments have
      been filled) get put into the list *mylist, which is commonly called *args
      (it's not a list, btw., it's a tuple), which in your case are all arguments
      behind the third.

      Hope this makes this somewhat clearer...

      Heiko.

      Comment

      Working...