* operator--as in *args?

7stud bbxx789_05ss at yahoo.com
Mon Mar 19 12:54:55 EDT 2007


On Mar 18, 7:52 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> def f(*args, **kw):
>
> ...   print "args",args
> ...   print "kw",kw
> ...>>> d = {"a":1, "b":2, "c":3}
> >>> f(**d)
>
Whoa! **?  And applied to a function parameter?  Back to the drawing
board.

On Mar 18, 7:21 pm, a... at mac.com (Alex Martelli) wrote:
> More generally, with any iterable x, the *x
> construct in function call will pass as positional arguments exactly
> those items which (e.g.) would be printed by the loop:
>     for item in x: print x
>

Thanks.

On Mar 18, 7:52 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> def f(*args, **kw):
>
> ...   print "args",args
> ...   print "kw",kw
> ...>>> d = {"a":1, "b":2, "c":3}
> >>> f(**d)
>
Whoa! **?  And applied to a function parameter name?  Back to the
drawing board.

The following is what I discovered for anyone else that is interested:

More on Defining Functions(GvR tutorial, section 4.7)
--Keyword Argument Lists
--Arbitrary Argument Lists
--Unpacking Argument Lists

1) Applying ** to a function parameter:

def g(a, b, **xtraArgs):
    print xtraArgs
g(b=20, c="big", a="hello", d=10)

#output: {'c': 'big', 'd': 10}

**xtraArgs will be a dictionary of all arguments sent to the function
with the syntax "keyword=value" if the keyword does not match any of
the function parameter names.

2)Applying * to a function parameter:

def g(a, *xtraArgs):
    print xtraArgs
g(10, 20, 30, 40)

#output: (20, 30, 40)

*xtraArgs will be a tuple containing all arguments sent to the
function with the syntax "value" that do not match any function
parameter.

3) A function parameter with the syntax *xtraArgs1 must come before a
function parameter with the syntax **xtraArgs2:

def g(a, b, *xtraArgs1, **xtraArgs2):
    print xtraArgs1
    print xtraArgs2

g(10, 20, 30, 35, d=40, e="hello")

#(30, 35)
#{'e': 'hello', 'd': 40}

4) Using * to unpack a list, tuple, etc.(any iterable collection--see
earlier posts):

def g(a, b, c):
    print a,b,c

tpl = (1, 2, 3)
g(*tpl)

#output: 1 2 3

5) Using ** to unpack dictionaries:

def g(a, b, c):
    print a,b,c

dict = {"b":"world", "c":"goodbye", "a":"hello"}
g(**dict)

#output: hello world goodbye








More information about the Python-list mailing list