Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Python function with partial parameters

Tags:

python

lambda

I want to pass a Python function to another function with some of its parameters "filled out" ahead of time.

This is simplification what I am doing:

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

def increment_factory(i):  # create a function that increments by i
    return (lambda y: add(i, y))

inc2 = increment_factory(2)

print inc2(3) # prints 5

I don't want to use some sort of passing of args and later exploding it with *args because the function I am passing inc2 into doesn't know to pass args to it.

This feels a bit too clever for a group project... is there a more straightforward or pythonic way to do this?

Thanks!

like image 329
Donald Miner Avatar asked Jul 15 '10 18:07

Donald Miner


People also ask

How do you create a partial function in Python?

You can create partial functions in python by using the partial function from the functools library. Partial functions allow one to derive a function with x parameters to a function with fewer parameters and fixed values set for the more limited function. This code will return 8.

What does partial () do in Python?

Implementing a Partial Function When called, partial() allows the program to output a function object resembling the original function with a fixed argument(s) passed into it.

How do you do partial functions?

A partial function allows us to call a second function with fixed values in certain arguments. For instance, we may have a function that computes an exponentiation. Then, we may need to create a new function that assigns a fixed value to either the base or the exponent.

Can a function have multiple parameters Python?

Python functions can have multiple parameters.


1 Answers

This is called currying, or partial application. You can use the built-in functools.partial(). Something like the following would do what you want.

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

inc2 = functools.partial(add, 2)
print inc2(3)
like image 168
David Avatar answered Sep 25 '22 09:09

David