0

I have a class with an init function that needs ~20 variables passed to it. Instantiations of the class are rather ugly:

some_var = MyClass(param1=mydict('param1')
                   param2=mydict('param2')
                   param3=mydict('param3')
                   ...
                   param20=mydict('param20')

I keep all of those parameters in a dictionary for easy handling already. Not all parameters are necessary so I don't want the class to accept only a dictionary object I don't think.

I'm wondering if I there's a nice trick to clean this up by specifying that the parameters to init are to be taken from the dictionary?

I'm just looking for tips and tricks on tidying this up a little. I have quite a few long/ugly instantiations of this class.

David Parks
  • 30,789
  • 47
  • 185
  • 328

1 Answers1

2

You can use keyword argument expansion:

some_var = MyClass(**mydict)
Oleksii Filonenko
  • 1,551
  • 1
  • 17
  • 27
James
  • 32,991
  • 4
  • 47
  • 70
  • 3
    Sounds dangerous... – juanpa.arrivillaga Apr 03 '17 at 18:14
  • Why would that be dangerous? Isnt it part of the language to unpack? – David Bern Apr 03 '17 at 18:15
  • @DavidBern sarcasm :) – Moses Koledoye Apr 03 '17 at 18:17
  • 1
    aaah. Im like Dr Sheldon Cooper. Dont understand sarcasm. Well, in that case, it was a funny remark – David Bern Apr 03 '17 at 18:18
  • 3
    I was making a joke about the use of "keyword explosion". I believe the author of this answer meant *expansion*. – juanpa.arrivillaga Apr 03 '17 at 18:21
  • There are like 20 variables, it does feel like an explosion. This is a new feature for me, so it's likely I know enough to be dangerous now. It certainly looks as pretty as I was hoping for, but then again so do mushroom clouds. – David Parks Apr 03 '17 at 21:13
  • Can I request a clarification on a more serious note? What if one parameter is missing from the dictionary? Does `MyClass(param21=True, **mydict)` work? What if I just want to override one parameter that *is* in the dictionary, does this work: `MyClass(param1=False, **mydict)`. What I mean to ask is whether I can have my cake and eat it too? – David Parks Apr 03 '17 at 21:15
  • That was easy enough to test. Adding parameters that don't exist in the dictionary works fine, but overriding dictionary parameters causes a "multiple values for keyword" exception. Also having extraneous values in the dictionary that aren't parameters of the function causes an exception. I can have my cake, eat it, but no frosting! – David Parks Apr 03 '17 at 23:33