3

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
  • 112,593
  • 23
  • 157
  • 280
Jgreen727
  • 55
  • 8

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
  • 181
  • 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
  • 1,937
  • 2
  • 6
  • 16
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
  • 823
  • 3
  • 18