0

My function is below:

def do(self, text, disable=['ner'], all_tokens=False, char_match=True, channels=use_channels)

Now I am using a Flask http call to make post requests to the function, and the function parameters are passed through the http call. The results of parameters is in a dict:

  parameters = {'disable':['ner', 'lst'], 'all_tokens':True, 'char_match':False}

My question is, how to apply the parameters in the dict to the function 'do'?

marlon
  • 6,029
  • 8
  • 42
  • 76
  • 2
    Watch out for [mutable default arguments](https://stackoverflow.com/q/1132941/4518341) like `disable=['ner']`. Unless you know what you're doing, that is. – wjandrea Jun 16 '20 at 23:26
  • Does this answer your question? [Passing a dictionary to a function as keyword parameters](https://stackoverflow.com/questions/334655/passing-a-dictionary-to-a-function-as-keyword-parameters) – wjandrea Jun 16 '20 at 23:30

1 Answers1

1

If I'm understanding you correctly, all you need to do is unpack the parameters object in the 'do' function. E.g.

do(**parameters)

If you're talking about how to pull the parameters from the URL-

You'll need to get them one at a time IIRC, but as follows:

from flask import request
disable = request.args.get('disable')
all_tokens = request.args.get('all_tokens')
...

do(..., disable=disable, all_tokens=all_tokens)
tomaszps
  • 66
  • 1
  • 6
  • tomaszps, so I need to redefine my do function using **parameters? My current function is defined without **, as you can see above. Also, I already convert my parameters into a dict, as shown above. – marlon Jun 16 '20 at 23:24
  • 1
    @marlon tomaszps is talking about *calling* the function, not defining it. Though FWIW you can define a function using the same syntax, like `foobar(**kwargs)`. *kwargs* is the conventional parameter name. – wjandrea Jun 16 '20 at 23:29
  • 1
    @wjandrea, if I call do(**parameters), what about other default parameters provided in the original function definition? The new parameters may only provide part of all the parameters. – marlon Jun 16 '20 at 23:32
  • @marlon Well, you'll need to pass `self` (though not explicitly since I assume `do` is an instance method) and `text`, but all the others have defaults so you don't need to provide them. – wjandrea Jun 16 '20 at 23:34
  • @wjandrea, in the link 'pass a dictionary to a function as parameter', there is one restriction: 'Number 2: You can not override a parameter that is already in the dictionary'. Then how to overwrite default parameter values? – marlon Jun 16 '20 at 23:43
  • 1
    @marlon You override default parameter values simply by passing them. I think you're confused about what that restriction means. Look at the example they give. For another example, you can reproduce the same problem easily with `print(end='', **{'end': ''})` – wjandrea Jun 16 '20 at 23:49