2

I have a working solution for what I am trying to achieve, but I am looking for simpler way to do it.

I have a class that encapsulates a function and a user can pass a function (lambda expression) to it. Those functions always take one input data argument and an arbitrary amount of user defined custom-arguments:

c.set_func(lambda x, offset, mul: mul*(x**2 + offset), offset=3, mul=1)

The user can then call a class method that will run the function with a predefined input and the currently set custom-arguments. The user also has the option to change the custom-arguments by just changing attributes of the class.

Here is my code:

from functools import partial

class C:
    def __init__(self):
        self.data = 10 # just an example
        self.func = None
        self.arg_keys = []

    def set_func(self, func, **kwargs):
        self.func = func

        for key, value in kwargs.iteritems():
            # add arguments to __dict__
            self.__dict__[key] = value
            self.arg_keys.append(key)
        # store a list of the argument names
        self.arg_keys = list(set(self.arg_keys))

    def run_function(self):
        # get all arguments from __dict__ that are in the stored argument-list
        argdict = {key: self.__dict__[key] for key in self.arg_keys} 
        f = partial(self.func, **argdict)
        return f(self.data)


if __name__ == '__main__':
    # Here is a testrun:
    c = C()
    c.set_func(lambda x, offset, mul: mul*(x**2 + offset), offset=3, mul=1)

    print c.run_function()
    # -> 103

    c.offset = 5
    print c.run_function()
    # -> 105

    c.mul = -1
    print c.run_function()
    # -> -105

The important part are:

  • that the user can initially set the function with any number of arguments
  • The values of those arguments are stored until changed

Is there any builtin or otherwise simpler solution to this?

duplode
  • 33,731
  • 7
  • 79
  • 150
Johannes
  • 3,300
  • 2
  • 20
  • 35
  • Dunno if it's simpler from your point of view, but you could use a function which uses static variables. – tim Jul 04 '17 at 16:14
  • You should IMO ask a moderator to migrate this question to the [Codereview Stack](https://codereview.stackexchange.com/) – try-catch-finally Jul 04 '17 at 19:28
  • There is context missing. How is that code intended to be used? Why can't the user directly use the constants in its "own" lambda? Probably because it should be called multiple times? What is the intention of passing the kwargs to `run_function()` _and_ assigning them as instance fields? Defaulting? – try-catch-finally Jul 04 '17 at 19:40

0 Answers0