Suppose I have a function foo(x,k) and suppose x is a list. I want k to default to the length of the list. Do I just write:
def foo(x, k=1):
k = len(x)
..
end
I just want to run foo with one argument, namely, x.
You should do:
def foo(x, k=None):
if k is None:
k = len(x)
...
Note that this could be made more compact as:
def foo(x, k=None):
k = k or len(x)
k=None then testing for None has always struck me as a construct for use with optional mutables mostly and use k=kwargs.get('k',len(l)) for others since in that one line you are testing and assigning. I didn't say it was wrong at all; just surprised**kwargs instead of a specific default keyword argument has a few disadvantages in this case. First, it's almost 25% slower according to a test I just did. (get is pretty slow.) Second, and more importantly, it disallows passing in k as a positional argument. Third, and most importantly, it accepts and silently ignores any keyword argument except k, whereas the above throws an error if passed an unexpected keyword argument.help(foo) less transparent.get is slower and your other arguments are correct. +1 for this and I have edited my post. I am here to learn...Just do:
def foo(x):
k = len(x)
You don't have to pass in k to this function. You can just use a local variable k.
In case you have to use k then you can just do:
def foo(x,k):
k = len(x)
Although this doesn't serve any purpose.
k should be an optional parameter. It should only take the value of len(x) if k is not supplied.If your intent is to have an optional k in no particular order with k=len(l) the default, you can use an optional keyword argument like so:
def f(l,**kwargs):
k=kwargs.get('k',len(l))
# if k is in kwargs, it overrides the default of len(l)..
print 'l={}, len(l)={}, k={}'.format(l,len(l),k)
f([1,2,3])
f([1,2,3],k=1)
Prints:
l=[1, 2, 3], len(l)=3, k=3
l=[1, 2, 3], len(l)=3, k=1
As pointed out in the comments, this is a trade-off with other considerations of speed and parameter position in David Robinson's approach.
kas internally declared variable, defaulting tolen(x)?kis always going to be the length of the list, why do you have it as an argument?foowith one argument. But your last sentence says that you only ever want to callfoowith one argument, which would makeka pointless parameter. Could you edit your question for clarity?