0

I have the following python function f1 that expects up to three parameters:

def f1(a = 0, b = 0, c = 0):
    return a + b + c

Now, I need to determine at runtime what parameters are passed to the function and their values.

For example, assume that the function needs to be called only with parameters a and c, ignoring b.

My code could look like

dict = { 'a': 1, 'c': 3}
print(f1(dict))  # <--- this should print 4

This doesn't work, but you get the idea. Is there a way to determine dynamically what parameters are used in a function call?

ps0604
  • 1,227
  • 23
  • 133
  • 330
  • 2
    Use `**` before the dictionary to unpack it when you use as parameter in a function call: `f1(**{"a": 1, "c": 3})`. This should result in `4`. – Carl HR Jul 13 '22 at 01:02
  • You can also use a single `*` before a list to unpack a list: `f1(*[1, 0, 3])`. This also returns `4`. – Carl HR Jul 13 '22 at 01:04
  • This is how most functions in python are defined: `def foo(*args, **kwargs)`. If you call `foo(1, 2, 3, a=4, b=5)`, inside `foo` you can access the values: `1 as args[0]`, `2 as args[1]`, `3 as args[2]`, `4 as kwargs["a"]` and `5 as kwargs["b"]`. – Carl HR Jul 13 '22 at 01:07
  • 2
    FYI, you might be getting parameters confused with arguments. Like, I'd say that function expects up to three *arguments* and has *exactly* three parameters. And they're specifically *keyword* arguments (otherwise you wouldn't be able to omit them out of order). – wjandrea Jul 13 '22 at 01:39
  • 1
    @CarlHR *"This is how most functions in python are defined"* -- Eh? Most functions aren't defined like that, only wrapper functions in my experience. Maybe you didn't phrase it very well. – wjandrea Jul 13 '22 at 01:42
  • Yep, I didn't phrase it well. But now I can't edit the comment anymore... – Carl HR Jul 13 '22 at 01:51

0 Answers0