Python alternative to Javascript function.bind()?

Question:

In Javascript, one might write

var ids = ['item0', 'item1', 'item2', 'item3']; // variable length
function click_callback(number, event)
{
    console.log('this is: ', number);
}
for (var k = 0; k < ids.length; k += 1)
{
    document.getElementById(ids[k]).onclick = click_callback.bind(null, k);
}

So I can pass to the callback function the value of k at the time it is registered even though it has changed by the time the function is called.

Does Python have a way to do something equivalent?


The specific situation is this (but I prefer a general answer):

I have a variable number of matplotlib plots (one for each coordinate). Each has a SpanSelector, which was for some reason designed to only pass the two limit points to the callback function. However, they all have the same callback function. So I have:

def span_selected(min, max):

but I need

def span_selected(which_coordinate, min, max):

At the time of registering the callback, I of course know the coordinate, but I need to know it when the function is called. In Javascript, I would do something like

callback = span_selected.bind(null, coordinate)

What would I do in Python?

Asked By: Mark

||

Answers:

Turned out it was already answered here: How to bind arguments to given values in Python functions?

The solution is:

from functools import partial
def f(a,b,c):
    print a,b,c
bound_f = partial(f,1)
bound_f(2,3)

Full credits to MattH.

EDIT: so in the example, instead of

callback = span_selected.bind(null, coordinate)

use

callback = partial(span_selected, coordinate)
Answered By: Mark
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.