3

I am using a module for a project, I have to pass a function to the module and the model does something like:

class module:
   def __init__(self, function, dictionary):
       # dictionary is {'x':2, 'y':4, 'z':23}
       function(**dictionary)

And my function is something like:

def function(*foo):
    return sum(foo)

The problem is that, the module needs named variables, and will pass it to the function like an unpacked dictionary, and the number of elements in dictionary can be variable, so I cannot pre-write the function as def function(x,y,z): return sum(x,y,z), and this raises an error. I do not wish to modify the module, because then, the code will not be universal. How can I solve this problem by just changing my code?

EDIT: I need foo as a list to use in the function

shiv_90
  • 1,025
  • 3
  • 12
  • 35

4 Answers4

3

You module that you can't change is calling your function with:

function(**dictionary)

You won't be able to write your function to the argument is a list — it's not being passed a list. You can accept the keywords as a dict and the easily make a list. Your function just needs to be prepared to be called that way:

def f(**foo):

This leads to:

class module:
    def __init__(self, function, dictionary):
       # dictionary is {'x':2, 'y':4, 'z':23}
       function(**dictionary)

def f(**foo):
    print(sum(foo.values()))

module(f, {'x':2, 'y':4, 'z':23})

# prints 29 as expected
Mark
  • 90,562
  • 7
  • 108
  • 148
0

It seems you want the sum of the values:

   def __init__(self, function, dictionary):
       # dictionary is {'x':2, 'y':4, 'z':23}
       function(dictionary.values())

The dictionary.values() will give a list of [2, 4, 23] for your example.

shiv_90
  • 1,025
  • 3
  • 12
  • 35
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
0
def function(*args,**Kwargs):
    try:
        return sum(*args)
    else:
        return sum(**kwargs.values())

double * unpacked dictionary values, and one * is to unpacked anything(except dictionary).

0

The number and type of arguments are determined by code of function init In your case this a single argument of type dictionary. So you have always to pass such function f(x) where x is a dictionary. So the that is function f that deals with the argument. E.g.

def fsum(x): return sum(x.values())
...
__init__(fsum, {'a': 1, 'b': 2, 'c': 3})
Yuri Ginsburg
  • 2,302
  • 2
  • 13
  • 16