[SciPy-User] List of functions with different arguments

Robert Kern robert.kern@gmail....
Fri Mar 1 14:01:47 CST 2013


On Fri, Mar 1, 2013 at 7:24 PM, Per Nielsen <evilper@gmail.com> wrote:
> Hi all
>
> I apologize if this is too off topic, but I figured it was common in
> scientific computing.
>
> I am trying to make a list of copies of the same function, but with
> different extra input arguments. However, I am having problems getting the
> wanted output. I thought it was a problem with the way I refered to the
> function, but I tried a deepcopy and also the functions seem to have
> different ids.
>
> Here is my output from the attached script:
>
> simple
> [3, 3, 3]
> [4549677376, 4549677496, 4549677616]
> deepcopy
> [3, 3, 3]
> [4549677736, 4549677856, 4549677976]
> wanted/expected output: [1, 2, 3]
>
> Any help would be greatly appreciated :)

You probably want to use functools.partial() for this.

  http://docs.python.org/2/library/functools#functools.partial

The problem you are encountering is that the lambda code block looks
up the variable `aa` from the global namespace at runtime, not
definition-time. The inner `for` loops for the list comprehensions
leak the `aa` variable so you end up with the last one in the global
namespace.

An alternative is to specify and bind the `aa` value as a keyword
argument to the lambda:

  fct_list = [lambda x, aa=aa: fct(x, aa) for aa in range(1, 4)]

--
Robert Kern


More information about the SciPy-User mailing list