1

I have a function in Python as

def myfunc(a, b=None, c=None):
    my code here

Is there a way to ensure that if the user passes the value of the parameter b it is necessary to pass the parameter c to myfunc?

S_S
  • 1,276
  • 4
  • 24
  • 47

2 Answers2

1

You can write a simple if condition in your function. See the code below:

def myfunc(a, b=None, c=None):
    if c is not None and b is None:
        raise ValueError("Value of b must be passed if value of c is passed")
    your code here
betelgeuse
  • 1,136
  • 3
  • 13
  • 25
1

Not in any built in way. Check it yourself:

def myfunc(a, b=None, c=None):
    if b is not None and c is None:
        raise ValueError("Invalid arguments")
    # ...
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
  • what if user has provided `None` as third argument, this will fail – sahasrara62 Nov 02 '21 at 06:22
  • @sahasrara62 If you supply a value that is the same as a default value, it's assumed you wanted whatever behavior the default value implies. – Ouroborus Nov 02 '21 at 06:34
  • it can be one of the case where c value passed in `None` in that sense for me atleast this solution doesn't make any sense – sahasrara62 Nov 02 '21 at 06:42
  • @sahasrara62 For a python function defined as `def func(a=None)`, calling it with either `func()`, `func(None)`, or `func(a=None)`, are all expected to have the same behavior. – Ouroborus Nov 02 '21 at 07:02