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

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


and this way:

Code: Select all

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


can't see any advantage of using ** to unpack
Posts: 15
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 for off-topic chat!

Please prefer not to PM members. The point of the forum is so that anyone can benefit. We don't want to help you over PMs/emails/Skype chats that others can't benefit from :)
User avatar
Posts: 2106
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 5 guests