Question on passing function as argument

xtian xtian at toysinabag.com
Tue Apr 1 07:21:31 CEST 2003


matthew <matthew at newsgroups.com> wrote in message news:<b6abiv$b6t$1 at lust.ihug.co.nz>...
> Hi,
> 
> Howto pass a func as an argument to a list?
> 
> event.add_listener('linear', [calc_position(params)])
> 
> the function seems to execute 'in-place' and the event_list[event] shows 
> None.

calc_position(params) is calling calc_position with params before
calling event.add_listener with the result (which is None, in this
case).

To pass a one element list containing the function object named
calc_position to your add_listener method (you might want to rename
that to add_listeners, by the way), you'd do the following:

event.add_listener('linear', [calc_position])

Leaving off the () means that the function isn't called, it's just
passed in.
Now, this isn't quite what you want - it doesn't pass the parameters.

If params is accessible from your notify method, you could just pass
it in when calling the function (guessing at the implementation of the
notify method...):

def notify(self, event, params):
    for listener in self.event_list[event]:
        listener(params)

If you won't be able to access params from notify, you'll need to
package the arguments with the function . You could do this in a
number of ways:

1) defining a local function:

def local_calc():
    calc_position(params)
event.add_listener('linear', [local_calc])

2) defining a local anonymous function:

event.add_listener('linear', [lambda: calc_position(params)])

3) by currying the function:

class SimpleCurry:
    def __init__(self, func, *args, **kw):
        self.func = func
        self.args = args
        self.kw = kw
    def __call__(self):
        return self.func(*self.args, **self.kw)

event.add_listener('linear', [SimpleCurry(calc_position, params)])

If you use one of these, the notify method changes to:

def notify(self, event):
    for listener in self.event_list[event]:
        listener()

Note - the first two options use nested scopes - I'm not sure whether
they're on by default in 2.1, but I don't think so. And the
func(*args, **kw) syntax used in 3 isn't available until then either.
If you're using an earlier version of Python (before 2.1), these
options will be spelt slightly differently, although using the same
basic concepts.

Hope that helps!
xtian




More information about the Python-list mailing list