Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

lambda - Creating Python function with partial parameters

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...