2

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?

4
  • I found the answer here on SO shortly after posting this (writing it down helps construct better search queries apparently). Should I delete the question as a duplicate, or answer it so other people who use javascript related search words might find the solution more easily? Commented Oct 7, 2013 at 5:27
  • I don't quite get what you mean by "one for each coordinate". If you have multiple plots, I think you should have a separate SpanSelector for each plot. Commented Oct 7, 2013 at 5:27
  • What is the duplicate question? Often better to mark it as duplicate so it's still findable as a signpost to the answer. Commented Oct 7, 2013 at 5:28
  • Okay I'll do that, and I'll edit to clarify the part about SpanSelectors Commented Oct 7, 2013 at 5:29

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.