Constraining a function by fixing an argument

How can I make a function with a lower dimension than the original one by fixing its argument:

For example, I want to make a successor function from the sum function as follows:

def add(x,y): return x+y 

Now I am looking for something like this:

g = f (~, 1), which would be a successor, i.e. g (x) = x + 1.

+3
function python bayesian-networks argument-passing belief-propagation
source share
2 answers

You can write your own function:

 def g(y): return f(2, y) 

Or more briefly:

 g = lambda y: f(2, y) 

There is also functools.partial :

 import functools def f(x, y): return x + y g = functools.partial(f, 2) 

Then you can call it as before:

 >>> g(3) 5 
+7
source share

If you do more than a little, then you can use something like a decorator.

 def with_x(x, fn, name=None): def foo(*args, **kwargs): return fn(x, *args, **kwargs) if name: foo.__name__ = name return foo def example(x,y): return x**y g = with_x(2, example) g(3) #8 

Use the name = parameter if you care about the name of the function to get. If necessary, you can introduce the built-in functions with other hacks, using, perhaps, the check module. But then you rewrote the previously mentioned functools component to avoid having to give keyword arguments.

+2
source share

All Articles