Search code examples
pythonpython-3.xsignature

Require parameter if another argument is present


Following is an example of what I would like to do.

def f(a, b, c):
    if a == 'method1':
        c = 0
    return b + c

In this function, parameter c is unneeded if the condition a='method1' is satisfied. Still, I can call the function with f(a='method1', b=1, c=2), which will have the same effect as f(a='method1', b=1, c=0).

A solution to this is to set the parameter c default to 0

def f(a, b, c=0):
    if a == 'method1':
        c = 0
    return b + c

Now I can call f(a='method1',b=1), which is exactly what I want. The problem is, I can still change the parameter c in the call f(a='method1',b=1,c=1), which I do not want the user to be able to.

Can I enforce this condition in the function signature, and not in the body (i.e. I would not like to use if in the body). Or if there is another better solution, please tell.

Something like

def f(a, b, c = 0 if a == 'method1', else c is required):
    return b + c

Thanks in advance.


Solution

  • a, b and c are all assigned dynamically at runtime. There is no way you can make up for this in the signature. It needs to be detected at runtime and you might as well do that in an if as anywhere else. You can specialize at the function name level, though, and python will take care of detecting the number of parameters.

    def f(b,c):
        return b + c
    
    def f_method1(b):
        return f(b, 0)
    
    def f_method2(half_a_c):
        return f(0, half_a_c*2)