Set default function parameter equal to another field of that function


I was wondering if I could something like this in Python:

def func(val1,val2=val1):
    #do whatever you want

I could do the following:

def func(val1,val2=None):
    val2 = val1 if val2 == None else val2
    #do whatever you want

But is there a more efficient/sexier way to do it?

Edit: I don’t think the linked question is close to what I am asking. What I am searching for is the right way to set a function’s default parameter value to the value of another parameter

Asked By: Xema



Checking if a parameter is None is done often in python where the parameter could be a mutable type.

By checking if none, it ensures that if the default type is a mutable type, an existing object isn’t used.

tl;dr, what you have seems pretty pythonic to me.

Answered By: Sayse
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.