2

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

2
  • 1
    if val2 == None else val2 => if val2 is None else val2 apart from that you're good. Commented Jun 19, 2017 at 8:20
  • From a result point of vue, it doesn't change anything. But thank you! Commented Jun 19, 2017 at 8:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.