0

I'm in a context where I have a dynamic objects as parameters and different classes to instantiate. I already managed how to load the classes into a dictionary, so I can instantiate any class passed as a string through command line, but I didn't figure it out how to "unpack" any object into parameters. E.g. the constructor of my Vectorizer class receives the following arguments:

Vectorizer(encoding=encoding, use_idf=True, norm='l2')

So, anytime the user indicates that this class must be instantiated, I also receive an object with the following example properties:

params = { "encoding":"utf8", "use_idf"=True, "norm"="l2"}

But I can not instantiate the Vectorizer like this:

Vectorizer(params)

I know a possible solution is doing refactoring in all existing classes and receiving a unique param containing all the propieries, but I would really like to avoid that, so I can keep the current descriptive constructors.

So, any idea about how to pass the params object as the required arguments?

Thanks in advance,

gal007
  • 6,911
  • 8
  • 47
  • 70
  • See [Passing a dictionary to a function as keyword parameters](https://stackoverflow.com/questions/334655/passing-a-dictionary-to-a-function-as-keyword-parameters) – glibdud Oct 08 '19 at 18:44

1 Answers1

2

The syntax is:

Vectorizer(**params)

This is called dictionary unpacking and is described in the manual.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • I swear you I tried before asking and didn't work in the console. But I tried again, this time on the script, and it worked. Thanks!! – gal007 Oct 08 '19 at 20:41
  • And thanks for indicating the concept and the docs!! I really wanted to know how to call it – gal007 Oct 08 '19 at 20:42