0

I need to forward a dictionary to another function (that I can't change). Both my function and the target function look like this:

def myFunc(arg, **args):
def targetFunc(arg, **args):

In my code, I used to call the target function directly:

a = targetFunc(123, aaa=4, bbb=5, ccc=6)

and I have to add another layer to process the extra arguments passed as a dictionary, before forwarding to the target function:

a = myFunc(123, aaa=4, bbb=5, ccc=6)

And now my function receives 123 as arg, and a dictionary:

{'bbb": 5, 'ccc': 6, 'aaa': 4}

as args. The problem is, I can't modify the target function in any way. It may be a function from a package like subprocess.run. I've tried supplying the dictionary directly but Python says

def myFunc(arg, **args):
    print(args)
    targetFunc(arg, args)

def targetFunc(arg, **args):
    print(args)
TypeError: targetFunc() takes 1 positional argument but 2 was given

I can write myFunc in any way. How can I forward this dictionary to the target function, so it receives the same dictionary as its args?

Note: It's possible to construct a string then eval() it, but I don't want to do it that way.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • 1
    `a = targetFunc(123, **{'bbb': 5, 'ccc': 6, 'aaa': 4})` – Aran-Fey Jan 30 '18 at 11:40
  • @MartijnPieters How is this question unclear? I'm just new to Python – iBug Jan 30 '18 at 11:44
  • @Rawing That works. It looks like a valid answer, could you please post it? – iBug Jan 30 '18 at 11:44
  • No need for an answer, we have plenty of duplicates for this. [Here](https://stackoverflow.com/questions/334655/passing-a-dictionary-to-a-function-in-python-as-keyword-parameters) and [here](https://stackoverflow.com/questions/21986194/how-to-pass-dictionary-items-as-function-arguments-in-python) for example. – Aran-Fey Jan 30 '18 at 11:48
  • @iBug: I'll re-open and close as a duplicate, but next time include a proper MCVE. You could have mocked up `targetFunc()` and a minimal implementation for `myFunc()` that reproduces the behaviour. – Martijn Pieters Jan 30 '18 at 13:07
  • @MartijnPieters I think the description is enough... Why do you think it lacks a MCVE? – iBug Jan 30 '18 at 13:08
  • 1
    We're programmers - code is easier for us to understand than words ;) – Aran-Fey Jan 30 '18 at 14:25

0 Answers0