Question

There is a function with a default value for a parameter:

def g(y, z = "default"):
    print  y, z

I want to call this function from a function "f", that among others should also contain a parameter "z", which shall be optional, i. e. the user of "f" should be able to call "f" with or without providing a value for "z". If he calls "f" without passing "z" in the argument list, "f" should call "g" so that the default value for "z" is used in the end. The value used as the default value (in this example "default") should occur only once in the code.

Was it helpful?

Solution

It sounds like your main goal is to make sure "default" only occurs once in the code.

def g(y, z = None):
    if z is None:
        z = "default"
    print y, z

def f(y, z = None):
    g(y, z)

OTHER TIPS

Use **kwargs:

def f(**kwargs):
    g("fixed-y", **kwargs)

f() # prints "fixed-y default"
f(z='mushroom') # prints "fixed-y mushroom"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top