In python, when passing arguments, what does ** do before the argument?

Possible duplicate:
What does * args and ** kwargs mean?

From reading this example and my subtle knowledge of Python, should it be a shortcut to convert an array to a dictionary or something else?

class hello: def GET(self, name): return render.hello(name=name) # Another way: #return render.hello(**locals()) 
+4
source share
4 answers

In python f(**d) , values ​​in the d dictionary are passed as keyword parameters for the f function. Similarly, f(*a) passes values ​​from the array a as positional parameters.

As an example:

 def f(count, msg): for i in range(count): print msg 

Call this function with **d or *a :

 >>> d = {'count': 2, 'msg': "abc"} >>> f(**d) abc abc >>> a = [1, "xyz"] >>> f(*a) xyz 
+11
source

It "unpacks" the dictionary as an argument list. i.e:

 def somefunction(keyword1, anotherkeyword): pass 

it could be called

 somefunction(keyword1=something, anotherkeyword=something) or as di = {'keyword1' : 'something', anotherkeyword : 'something'} somefunction(**di) 
+1
source

From Python Documentation, 5.3.4 :

If any keyword argument does not match the formal parameter name, a TypeError exception is thrown if there is no formal parameter using the syntactic ** identifier; in this case, this formal parameter receives a dictionary containing redundant keyword arguments (using keywords as keys and argument values ​​as corresponding values) or a (new) empty dictionary if there were no extra keyword arguments.

It is also used for the power operator in a different context.

+1
source

** local () passes the dictionary corresponding to the local namespace of the caller. When passing a function with **, a dictionary is passed, this allows the use of variable-length argument lists.

+1
source

All Articles