AngusTheMan
AngusTheMan

Reputation: 582

Using callbacks inside a function callback

Given the following three functions:

def return_arg( *arg ):
    return arg[0]

def an_expression( x, y, **kwargs ):
    return x*x + y*y

def sub_function( x, y, F ): 
       return x + y + F(**locals())

I can call the following sub_function( 1, 2, an_expression ) to obtain 8.

I can also call:

T = 5
return_arg(T)

How can I call

sub_function( 1, 2, return_arg)

in the case that I want to have return_arg(T)?

Upvotes: 0

Views: 40

Answers (2)

RishiG
RishiG

Reputation: 2830

Another option is to pass args and/or kwargs to your callback evaluator

def sub_function( x, y, F, *args, **kwargs): 
       return x + y + F(*args, **kwargs)

Then you can call it however you want, e.g.,

sub_function( 1, 2, return_arg, 5)

Upvotes: 1

TwistedSim
TwistedSim

Reputation: 2030

I'm not sure I understood fully your question, but I think what you need is partial function:

from functools import partial
my_partial = partial(return_arg, T)
sub_function( 1, 2, my_partial)

Upvotes: 1

Related Questions