Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set a default parameter equal to another parameter value?

For example, I have a basic method that will return a list of permutations.

import itertools def perms(elements, set_length=elements):     data=[]     for x in range(elements):         data.append(x+1)     return list(itertools.permutations(data, set_length)) 

Now I understand, that in its current state this code won't run because the second elements isn't defined, but is there and elegant way to accomplish what I'm trying to do here? If that's still not clear, I want to make the default setLength value equal to the first argument passed in. Thanks.

like image 848
CopOnTheRun Avatar asked Jun 17 '13 21:06

CopOnTheRun


People also ask

Can you assign the default values to a function parameters?

Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

Can there be more than one default parameter in a function?

Only one parameter of a function can be a default parameter. B. Minimum one parameter of a function must be a default parameter.

Can out parameter have a default value?

The designers considered the feature and rejected it as not useful enough to be worth the cost of implementing. The designers considered the feature and rejected it as being confusing because it uses similar syntax to default value parameters, but has a quite different meaning.


2 Answers

No, function keyword parameter defaults are determined when the function is defined, not when the function is executed.

Set the default to None and detect that:

def perms(elements, setLength=None):     if setLength is None:         setLength = elements 

If you need to be able to specify None as a argument, use a different sentinel value:

_sentinel = object()  def perms(elements, setLength=_sentinel):     if setLength is _sentinel:         setLength = elements 

Now callers can set setLength to None and it won't be seen as the default.

like image 122
Martijn Pieters Avatar answered Sep 21 '22 19:09

Martijn Pieters


Because of the way Python handles bindings and default parameters...

The standard way is:

def perms(elements, setLength=None):     if setLength is None:         setLength = elements 

And another option is:

def perms(elements, **kwargs):     setLength = kwargs.pop('setLength', elements) 

Although this requires you to explicitly use perms(elements, setLength='something else') if you don't want a default...

like image 24
Jon Clements Avatar answered Sep 18 '22 19:09

Jon Clements