Skip to main content
GameDev.net gamedev.net
🔒 Locked

what is **varkw in Python

Started by Lucidquiet Apr 8, 2006 at 2:44 PM 2 replies 1.8k views
Original Post
Lucidquiet
Lucidquiet
The inspect.getargspec(func) returns a tuple of 4 things (args, varargs, varkw, and defaults). The arguments is just the names of the parameters; varargs the variable length arguments given to the function; and defaults is the default value any of the parameters... I've not found any explanation as to what varkw is, and what its for... I think I read that it might stand for var key words... I'm still looking though. But help is always appreciated, Thanks, L-
"Education is when you read the fine print; experience is what you get when you don't." -Pete Seegerwww.lucid-edge.net
Fruny
Fruny
Consider a function defined as: def foo(a, b, c, *args).

When calling the function first three parameters will be placed in a, b, and c respectively. Any additional parameter will be stored in args as a list:
foo(1,2,3)       → a=1, b=2, c=3, args=[]foo(1,2,3,4,5,6) → a=1, b=2, c=3, args=[4,5,6]


Now consider a function defined as: def foo(a, b, c, **args).

args will gather "keyword arguments" in a dictionary:
foo(1,2,3)              → a=2, b=2, c=3, args = {}foo(1,2,3,n=3,u=42,z=6) → a=1, b=2, c=3, args = { 'n':3, 'u':42, 'z':6 }


Of course, if you have both *args and **kwargs in your parameter list, things get a bit more complicated, but that's the gist of it.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Fruny
Fruny
Note that there also is a symmetrical usage of * and ** that lets you pass a list or a dict respectively, and have them "expand" into the function's parameters.

def foo(a,b,c):    passm = [1,2,3]foo(*m)     # a=1, b=2, c=3n = {'a':1, 'b':2, 'c':3 }foo(**n)    # a=1, b=2, c=3




See here for details.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Lucidquiet
Lucidquiet
Very cool, thanks a lot.

L-
"Education is when you read the fine print; experience is what you get when you don't." -Pete Seegerwww.lucid-edge.net

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.