Search code examples
pythonfunctionparameterskeyword-argumentnested-function

Calling several functions with different default parameters from a function modifying the default values


I have several functions with default parameters, which are called from a high-level function and I would like to be able to modify a certain number of those parameters from the other functions. Let's put an example

def printing(what, n = 3):
    for _ in range(n):
        print(what)

def printing_number(number, i=3):
    for _ in range(i):
        print(number)

def outer(what, number):
    printing(what)
    printing_number(number)

outer is the function that is going to be called and I would like to being able to put something like outer('hello', 4, i = 4) and then it will execute printing('hello', n=3) and printing_number(4, i=4).

I have tried with **kwargs as follows:

def printing(what, n = 3):
    for _ in range(n):
        print(what)

def printing_number(number, i=3):
    for _ in range(i):
        print(number)
def outer(what, number, **kwargs):
    printing(what, **kwargs)
    printing_number(number, **kwargs)

However, it just works correctly with the default parameter, if I code outer('hello',3,i=4), I will get an error saying that printing received an unexpected parameter.

So, is there a way that i is passed only to the function that has it as parameter?


Solution

  • Problem seems to be the fact that you are calling printing(what, **kwargs) but do not have the **kwargs keyword in the function definition. Just add **kwargs to your first function and things work fine

    def printing(what, n = 3, **kwargs):
        for _ in range(n):
            print(what)
    
    
    outer('hello', 4, i = 4)   
    # hello
    # hello
    # hello
    # 4
    # 4
    # 4
    # 4