Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook:
def get(self, *a, **kw)
Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find a satisfactory answer).
Thank you very much.
-
See Function Definitions in the Language Reference.
If the form
*identifier
is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form**identifier
is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.Also, see Function Calls.
-
A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.
Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.
def f0(a) def f1(*a) def f2(**a) def f3(*a, **b) etc...
Jason Baker : Not to nit-pick, but if you use a single star, the argument is stored as a tuple, not a list. -
I only have one thing to add that wasn't clear from the other answers (for completeness's sake).
You may also use the stars when calling the function. For example, say you have code like this:
>>> def foo(*args): ... print(args) ... >>> l = [1,2,3,4,5]
You can pass the list l into foo like so...
>>> foo(*l) (1, 2, 3, 4, 5)
You can do the same for dictionaries...
>>> def foo(**argd): ... print(argd) ... >>> d = {'a' : 'b', 'c' : 'd'} >>> foo(**d) {'a': 'b', 'c': 'd'}
-
I find * useful when writing a function that takes another callback function as a parameter:
def some_function(parm1, parm2, callback, *callback_args): a = 1 b = 2 ... callback(a, b, *callback_args) ...
That way, callers can pass in arbitrary extra parameters that will be passed through to their callback function. The nice thing is that the callback function can use normal function parameters. That is, it doesn't need to use the * syntax at all. Here's an example:
def my_callback_function(a, b, x, y, z): ... x = 5 y = 6 z = 7 some_function('parm1', 'parm2', my_callback_function, x, y, z)
Of course, closures provide another way of doing the same thing without requiring you to pass x, y, and z through some_function() and into my_callback_function().
-
All of the above answers were perfectly clear and complete, but just for the record I'd like to confirm that the meaning of * and ** in python has absolutely no similarity with the meaning of similar-looking operators in C.
They are called the argument-unpacking and keyword-argument-unpacking operators.
0 comments:
Post a Comment