Unpacking arguments

This is the place for queries that don't fit in any of the other categories.

Unpacking arguments

Postby verb » Fri Aug 23, 2013 5:12 pm

Hello everyone
i have been wondering which way is better to unpack dictionary passed to function and is there any difference in doing unpacking this way:

Code: Select all
dice={1:'one','2':'two','3':'three'}
num=1

def funk(a,kargs):
    print a,"\n"
    print kargs

funk(num,dice)


and this way:

Code: Select all
dice={'1':'one','2':'two','3':'three'}
num=1

def funk(a,**kargs):
    print a,"\n"
    print kargs

funk(num,**dice)


can't see any advantage of using ** to unpack
verb
 
Posts: 9
Joined: Fri Feb 22, 2013 8:15 pm

Re: Unpacking arguments

Postby micseydel » Fri Aug 23, 2013 6:10 pm

You use the kwargs variable inside the function to get access to unpredictable keyword arguments.
Code: Select all
def f(**kwargs):
    for name, title in kwargs.iteritems():
        print "{} is {}".format(name, title)

f(michael="a software engineer", obama="the president")

You use double star on passing it to the function when you have a dictionary and want to pass it it but can't do it explicitly as I did above, but want it to be used the same inside the function.
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 941
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests