Search code examples
pythonfunctionnamed-parameters

How to pass a parameter as a default?


I want to use the default of a parameter, but include its name in the call. I thought that setting the parameter to None would do that, but it doesn't.

For example:

def a(num=3):
    print(num)

a(num=None) #returns "None", not "3" like I want it to.

How can I use the default of a named parameter while including it in the call? (Is it even possible?)

Just to explain why I would want to do something like this (since maybe it's a problem in my overall coding style):

I often times have code like this

def add(num, numToAdd=1):
    return num+numToAdd

def addTwice(num, numToAdd=None):
    for i in range(2):
        num=add(num, numToAdd=numToAdd)
    return num

addTwice(3) #throws an error instead of returning 5

What I want is for addTwice's numToAdd to always use the default of add's numToAdd, no matter what it is.

The reason: maybe later in the code I realize that it's better to add 2 as the default when executing add than it is to add 1.

So I change it to

def add(num, numToAdd=2):
        return num+numToAdd

But, this won't help anything unless I can always specify in addTwice to use the default if it receives a default.

So, that's the rationale.

In other words: I'm having a function (the first function) call another function (the second function), and if the first function has to use a default value, I want it to default to being the default value on the second function. That way, I only have to change the default value on the second function (not every single function that calls it as well) in order to change the default functionality.


Solution

  • There is a great answer on how to do this (if you decide that the default-getting functionality I asked for is really what you want). But, I just wanted to point out that in practice I believe what I was trying to achieve is normally done with global variables.

    That is, the usual way to do what I wanted to do is:

    DEFAULT_NUM_TO_ADD = 1
    def add(num, numToAdd=DEFAULT_NUM_TO_ADD):
        return num+numToAdd
    
    def addTwice(num, numToAdd=DEFAULT_NUM_TO_ADD):
        for i in range(2):
            num=add(num, numToAdd=numToAdd)
        return num
    
    addTwice(3) # returns 5
    

    This allows me to quickly change the default, and the same default is used for both functions. It's explicit and very clear; it's pythonic.