Search code examples
pythondefaultoptional-parameters

Python - how to set default parameter equal to another parameter


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


Solution

  • 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, [] ...)