[issue27738] odd behavior in creating list of lambda expressions

2016-08-12 Thread John Sahr

John Sahr added the comment:

I eventually figured that out that source of the problem;

thanks for the coding fix; that's useful to know.

-John

On Thu, Aug 11, 2016 at 8:17 AM, Emanuel Barry 
wrote:

>
> Emanuel Barry added the comment:
>
> This is due to the fact that Python evaluates the variable 'n' when the
> function is called, not when it is created. As such, the variable holds the
> latest value for all functions, and they exhibit identical behaviour.
>
> Workaround:
>
> ...
> f = lambda x, n=n: sin(n*x)
> ...
>
> And this should work as you expect. More information is available at
> https://docs.python.org/3/faq/programming.html#why-do-
> lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
>
> --
> nosy: +ebarry
> resolution:  -> not a bug
> stage:  -> resolved
> status: open -> closed
> versions:  -Python 2.7
>
> ___
> Python tracker 
> 
> ___
>

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27738] odd behavior in creating list of lambda expressions

2016-08-11 Thread John Sahr

New submission from John Sahr:

The following produces unexpected behavior.
I think that it should produce a list of six different lambda expressions,
but after creation, all six lambda expressions produce the same output.
It's possible that I'm missing something about Python.

# begin example ###
from math import *

mm = []

for n in range(6):
f = lambda x: sin(n*x)
print f, f(1.0)
mm.append(f)

print '***'

for m in mm:
print m, m(1.0)
## end example 

--
messages: 272454
nosy: John Sahr
priority: normal
severity: normal
status: open
title: odd behavior in creating list of lambda expressions
type: behavior
versions: Python 2.7

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27738] odd behavior in creating list of lambda expressions

2016-08-11 Thread Emanuel Barry

Emanuel Barry added the comment:

This is due to the fact that Python evaluates the variable 'n' when the 
function is called, not when it is created. As such, the variable holds the 
latest value for all functions, and they exhibit identical behaviour.

Workaround:

...
f = lambda x, n=n: sin(n*x)
...

And this should work as you expect. More information is available at 
https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result

--
nosy: +ebarry
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed
versions:  -Python 2.7

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com