Function restriction by fixing an argument

Question:

How should I make function with lesser dimensionality than the original one by fixing an
argument of it:

For example I want to make successor function out of 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 the successor function, i.e. g(x) = x+1.

Asked By: Cupitor

||

Answers:

You can write your own function:

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

Or more concisely:

g = lambda y: f(2, y)

There’s also functools.partial:

import functools

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

g = functools.partial(f, 2)

You can then call it as before:

>>> g(3)
5
Answered By: Blender

If you do more than a little of this then you could 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 name = parameter if you care about the __name__ of the resulting function. You could get fancier with other hacks into the enclosed function innards possibly using the __inspect__ module if need be. But then you have re-written the previously mentioned functools partial stuff just to avoid having to give keyword arguments.

Answered By: user1969453