Argument Precedence (possible bug?)

vbgunz vbgunz at gmail.com
Mon Mar 6 13:07:50 EST 2006


Hello, Steven D'Aprano, Terry Jan Reedy!

I would really like to extend my thanks to you guys. I hope I've got it
right this time!

def posKeyArgs(a, b=2, c=3):
    print a, b, c

#posKeyArgs(b=20)  # too few positional arguments. a needs an arg.
#posKeyArgs(10, c=30, 20)  # pos_args cannot follow any kw_args.

def specialArgs(*args, **kwargs):  # Can't call these keywords!
    print args
    print kwargs

specialArgs(args='arg1', kwargs='kwargs')  # Keywords match nothing.
specialArgs('string')  # not converted. Collected into: ('string',)

The above can begin to explain why I had problems with my first
example. *args and **kwargs cannot have arguments assigned to them by
keyword. Once an argument is matched by keyword, all following
arguments must also be matched by keyword.

This would explain why using only positional arguments, my first
example would have worked right out of the box. Because, all
positionals would have matched first, then all left overs would have
been collected into *args, then finally any keyword args would be
collected into **kwargs.

So far the general consensus also seems to be not to over complicate a
function definition with such parameters. This makes sense and is why I
chose Python over many other options. I love the idea of explicit over
implicit :) Again though, my first example was only a personal
reference.

Fellas, thank you all so much for helping me understand this much
better. You guys are my angels of Python for sure!




More information about the Python-list mailing list