0

I have a function, which should have one optional parameter. I want the optional parameter to be the same as other parameter. Something like this:

def foo(arg1, arg2, src, dst=src):
  ...
  ...

Parameter dst is the optional one. The thing is when dst is not given when calling foo, it should be same as src.

Any ideas?

Thank you

1 Answer 1

3

How about this?

def foo(arg1, arg2, src, dst=None):
    dst = dst if dst is not None else src

Test:

>>> def foo(arg1, arg2, src, dst=None):
...     dst = dst if dst is not None else src
...     print dst
... 
>>> foo(0, 0, "test")
test

Following @TanveerAlam 's comment, I don't want to make assumptions about your arguments (what if dst can be False?), I did use shorter versions in my original post and I'll leave them here for reference:

def foo(arg1, arg2, src, dst=None):
    dst = dst if dst else src

Or even:

def foo(arg1, arg2, src, dst=None):
    dst = dst or src

Note that these versions will prevent values other than None in dst (like False, [] ...)

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

2 Comments

dst = dst if dst else src this would work too as bool value of None is False.
I would prefer dst = dst or src. A bit more clear and less repetitive, and relies on the same behaviour as dst if dst else src

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.