0

Let's say I have the following function:

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

I would like to bind x=2 and y=2 to the function but not actually call it. What is the correct way to do this? I've done this sometimes with add_bound=lambda: add(2,3), but I'm wondering if this is the 'pythonic' approach or there is another way to do it (perhaps binding certain arguments, and then passing other arguments later.

David542
  • 104,438
  • 178
  • 489
  • 842
  • 2
    Does this answer your question? [Python Argument Binders](https://stackoverflow.com/questions/277922/python-argument-binders) – mkrieger1 Apr 06 '21 at 23:33

2 Answers2

0

Often this will be done with a decorator. Here is a general example:

add = lambda x,y: x+y

def wrap(outer_func, *outer_args, **outer_kwargs):
    def inner_func(*inner_args, **inner_kwargs):
        args = list(outer_args) + list(inner_args)
        kwargs = {**outer_kwargs, **inner_kwargs}
        return outer_func(*args, **kwargs)
    return inner_func

In this case you can do things such as the following:

# pass both at once
>>> x=wrap(add,2,3)
>>> x()
5

# pass one at binding, second at call
>>> x=wrap(add,2)
>>> x(3)
5

# pass both when called
>>> x=wrap(add)
>>> x(2,3)
5

Note that the above is very similar to functools.partial:

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

from functools import partial
basetwo = partial(int, base=2)
basetwo.__doc__ = 'Convert base 2 string to an int.'
basetwo('10010')
18
David542
  • 104,438
  • 178
  • 489
  • 842
-1
def add(x=2, y=2):
    return x+y
e.tipsin
  • 36
  • 1