0

I have a function that can take either 1 string or 4 strings:

def my_function(a, b, c, d, e):

I want the user to either pass in a, or to pass in b, c, d and e. I know that I can make them all default to None, but then I need to have logic in my code that ensures that we either get only a, or that we get values for all of b, c, d and e.

Is there a better way to structure this? I really don't want to have two different methods, but that is also a possibility.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Mark
  • 2,058
  • 2
  • 35
  • 64
  • 2
    Having two methods is the proper way to do this. Packing this much logic into a single function makes things very difficult to reason about https://stackoverflow.com/questions/6434482/python-function-overloading – sinanspd Feb 12 '21 at 22:04
  • 2
    What should happen if the user provides values for `a`, `b`, `c`, `d` and `e`? It sounds inevitable that you'll need to validate the arguments *at some point*, either inside `my_function` or before calling it. Without looking at the specific needs of your code, I'd say it's better to validate the arguments in another method, and then call `my_function_a` or `my_function_bcde`, depending on the validation resuts. – jfaccioni Feb 12 '21 at 22:34

1 Answers1

0

Not 100% sure if this is what you're going for.

But this could work:

def my_function(*args):
    if len(args) == 1:
        a = args[0]
        # do stuff with a
    elif len(args) == 4:
        (b, c, d, e) = args
        # do stuff with b,c,d,e
    else:
        raise Exception("Expected 1 or 4 arguments: Got " + str(len(args)))

Farhaan S.
  • 104
  • 5