Argument Precedence (possible bug?)

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Mar 5 08:47:12 EST 2006


On Sun, 05 Mar 2006 04:45:05 -0800, vbgunz wrote:

> PS. I could be far off with this codes purpose; to try and create an
> example that will house all the different possible parameters
> (positional, keyword, * and **) in one single def statement.

This is usually a bad idea, not because Python can't cope with it, but
because it is usually better to learn new things in small pieces, not one
giant enormous piece.

Try creating a number of small functions that do different things:

def f(a, b, c):
    print "a =", a, "b =", b, "c =", c

def g(a=0, b=0, c=0):
    print "a =", a, "b =", b, "c =", c

Now call them different ways, and see what happens:

f()
f(1)
f(1,2)
f(1,2,3)
f(b=2)

Can you see a pattern?

g()
g(1)
g(1,2)
g(1,2,3)
g(b=2)

Then move on to argument collectors:

def h(a, b, c=0, *d, **e):
    print "a =", a, "b =", b, "c =", c
    print "d =", d, "e =", e



Also, remember that "positional arguments" and "keyword arguments" aren't
defined differently, they are given when you call the function. For
example, suppose you have this:

def function(x, y):
    print x + y

Now you call it with positional arguments: function(3, 7)
Now you call it with keyword arguments: function(x=3, y=7)
Now you call it with both: function(3, y=7)

All from the same definition. An argument is positional or keyword
according to how it is given, not how it is defined.


-- 
Steven.




More information about the Python-list mailing list