Search code examples
pythonfunctiondefaultdefault-value

Using default values in Python mixed with input parameters


I have function that looks like this:

def CreateURL(port=8082,ip_addr ='localhost',request='sth'):
    return str("http://" + ip_addr+":"+str(port) + '/' + request)

Now I want to use the default parameter for port and request but not for ip_addr. How do I have to write the function in this case?

CreateURL('192.168.2.1')

Does not work since itwill override the port and not the ip_addr


Solution

  • Pass the parameter explicitly.

    >>> def foo(a=1, b=2, c=3):
    ...     print(a, b, c)
    ... 
    >>> foo(c=4)
    (1, 2, 4)