4

Is there a way to set a default parameter value in a function to be another one of the parameters?

I.e.

def (input1, input2 = input1)

I figure I can do something like what’s shown below, but want to know if there’s a better way

def (input1, input2 = 'blank')
      If input2 == 'blank':
           input2 = input1
martineau
  • 119,623
  • 25
  • 170
  • 301
Jgreen727
  • 75
  • 9

3 Answers3

3

You could try this. Maybe a little more clarification could help us help you more.

def do_stuff(input1, input2 = None):
    if input2 is None:
       input2 = input1

You were pretty close.

Peter Jones
  • 191
  • 5
2

You cannot assign a local variable to an argument, as the variable is not yet defined during the definition of the function.

We usually use None to catch a missing value:

def add2(i1, i2=None):
    if i2 is None:
        i2 = i1
    return i1 + i2

In this function, i1 will be mandatory. If not provided, i2 will be set to the same value as i1.

add2(10, 2)
# > 12
add2(9)
# > 18
Whole Brain
  • 2,097
  • 2
  • 8
  • 18
0

I prefer to use create a class as the parameter

class helper:
    input 2 = 'blank'
    input 3 = 1
def xx(input1, helper):
    if input1 == helper.input2:
        input1 == helper.input3

This is an example, you can use a class to help you.

Zichzheng
  • 1,090
  • 7
  • 25