I have a lot of confusion in trying to use either lambda or functools.partial to create a new function with related positional arguments from an existing function.
I want to do something like this (which does not behave as desired):
def addFunction(self, name, in_function, secondary_args=None, secondary_kwargs=None): # Assign the function with optional args based on whether any # optional args are not None if secondary_args is not None and secondary_kwargs is not None: func = lambda x: in_function(x, *secondary_args, **secondary_kwargs) elif secondary_args is None and secondary_kwargs is not None: func = lambda x: in_function(x, **secondary_kwargs) elif secondary_args is not None and secondary_kwargs is None: func = lambda x: in_function(x, *secondary_args) else: func = in_function ### func.__doc__ = in_function.__doc__ self[name] = func # <-- This method is a class method for something deriving dict.
I also tried replacing all lambda statements with equivalent functools.partial .
The problem is that if I use this function as follows:
# Assume some_function takes 3 arguments, a float, a Bool, and a String, # in that order. someObject.addFunction("my_f", some_function, secondary_args=[True, "Option_A"])
now when I try to use (for example) someObject["my_f"](5.0) , it reports that the first argument is True when I debug it.
It seems that the bindings, either with lambda or with partial simply insert positional arguments and either take your extra positional argument at the end of *args , or just discard it (I'm not sure which one).
For my application, since many functions will be stored in a specific object like this, with a different number of optional arguments chosen by the user, it is important that the function I return with bound arguments still accepts the user argument as the first positional argument, without resorting to all arguments were keyword arguments.
It seems like it should be simple enough. What am I missing?