0

I have a function, which has a bunch (~25) parameters. However, I usually want to use the default value of most of those parameters, and only specify a couple (to have values other than their defaults). So I've been doing something like (same idea, but fewer parameters for this example):

def myFn(self,a=20,b=10,c=5):
    self.a = a
    self.b = b
    self.c = c

myFn(a=100)

Which will give a the value 100 and leave b and c with their default values.

And this has worked till now. However, it's getting cumbersome, having a million parameters in the function definition, and also if I call the function with a ton of arguments.

Is there a better way to do this? I know that you can pass keyword arguments, as a dict, which is almost what I want I think. But how can you then give default values inside the function?

edit: this is not a duplicate of What does ** (double star/asterisk) and * (star/asterisk) do for parameters? as that doesn't help me with what you should do with defaults.

GrundleMoof
  • 289
  • 3
  • 11

1 Answers1

1

Use **kwargs and call .get() with the desired default value for each item.

def myFn(self, **kwargs):
    self.a = kwargs.get('a', 20)
    self.b = kwargs.get('b', 10)
    self.c = kwargs.get('c', 5)
John Gordon
  • 29,573
  • 7
  • 33
  • 58