[issue45930] Lambda function bug

2021-11-29 Thread Eric V. Smith


Change by Eric V. Smith :


--
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed
type:  -> behavior

___
Python tracker 

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



[issue45930] Lambda function bug

2021-11-29 Thread Karthikeyan Singaravelan


Karthikeyan Singaravelan  added the comment:

This is known behaviour due to binding. Please see  
https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result

--
nosy: +xtreak

___
Python tracker 

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



[issue45930] Lambda function bug

2021-11-29 Thread Valery Lovchikov


New submission from Valery Lovchikov :

Python 3.9.7 (default, Sep 10 2021, 14:59:43) 
[GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f=[lambda x: y**x for y in [2,3]]
>>> f[0](2)
9
>>> f[1](2)
9
=
I expected 4 as a result of f[0](2), but got 9

--
messages: 407293
nosy: lvch
priority: normal
severity: normal
status: open
title: Lambda function bug
versions: Python 3.9

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



Re: Error in lambda function..!

2020-08-29 Thread Rob Cliffe via Python-list



On 29/08/2020 08:58, Shivlal Sharma wrote:

from functools import*
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
add = reduce(lambda a : a + 1, nums)
print(add)

error: -
TypeError Traceback (most recent call last)
 in ()
   1 from functools import*
   2 nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> 3 add = reduce(lambda a : a + 1, nums)
   4 print(add)

TypeError: () takes 1 positional argument but 2 were given

When you write
    lambda a :
you are defining a function that takes **one** argument, viz. a.
It's the same as if you wrote:
    def myfunc(a): return a+1
and then
    add = reduce(myfunc, nums)
But reduce always calls your supplied function with **two** arguments.  
Hence the error.

I don't know exactly what you are trying to do, but if you wrote
    add = reduce(lambda a,b: a+1, nums)
or equivalently
    def myfunc(a,b): return a+1
    add = reduce(myfunc, nums)
reduce would call your lambda function succesively with arguments
    (1,2)    # which would return 1+1 i.e. 2
    (2,3)    # use previous result (2) and next number in the sequence 
(3); returns 2+1 i.e. 3

    (3,4)    # use previous result (3) and next number in the sequence (4)

    .
    (8,9)    # returns 8+! i.e. 9
and finally 9 would be printed.

If you want to watch what is happening try
    def myfunc(a,b):
        print(f"Myfunc({a},{b})")
        return a+1
    add = reduce(myfunc, nums)

Try
    from functools import *
    help(reduce)
for an explanation of how reduce works.  Note that the first sentence 
starts "Apply a function of two arguments"

Best wishes
Rob Cliffe

--
https://mail.python.org/mailman/listinfo/python-list


Re: Error in lambda function..!

2020-08-29 Thread Peter Otten
Shivlal Sharma wrote:

> from functools import*
> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> add = reduce(lambda a : a + 1, nums)
> print(add)
> 
> error: -
> TypeError Traceback (most recent call
> last)  in ()
>   1 from functools import*
>   2 nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> > 3 add = reduce(lambda a : a + 1, nums)
>   4 print(add)
> 
> TypeError: () takes 1 positional argument but 2 were given

Read the error message: your lambda accepts ony one argument, but reduce 
tries to pass two to it. That you don't need the second argument doesn't 
mean that you can it omit it, so:

>>> from functools import reduce
>>> reduce(lambda a, b: a + 1, range(1, 10))
9


-- 
https://mail.python.org/mailman/listinfo/python-list


Error in lambda function..!

2020-08-29 Thread Shivlal Sharma
from functools import*
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
add = reduce(lambda a : a + 1, nums)
print(add)

error: -
TypeError Traceback (most recent call last)
 in ()
  1 from functools import*
  2 nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> 3 add = reduce(lambda a : a + 1, nums)
  4 print(add)

TypeError: () takes 1 positional argument but 2 were given
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue30852] _PyObject_GC_UNTRACK corruption when call a lambda function with C API

2020-06-25 Thread STINNER Victor


STINNER Victor  added the comment:

I close the issue since it has no activity since 2017.

If you get a similar issue, I suggest to test a debug build of Python. The ABI 
is compatible with release build since Python 3.8.

--
nosy: +vstinner
resolution:  -> out of date
stage:  -> resolved
status: open -> closed

___
Python tracker 

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



[issue30852] _PyObject_GC_UNTRACK corruption when call a lambda function with C API

2017-07-04 Thread 盛茂家

New submission from 盛茂家:

This corruption is so strange that I can't even reappear it.

(gdb) bt
#0  0x006d7e9f in func_dealloc.lto_priv () at Objects/funcobject.c:451
#1  0x005c730b in ask (printException=true, okIfFunctionNull=, errorPrefix=0x884bca "", pArgs=0x300dd440, pFunction=0x1d1f1de8) at 
script.cpp:758
#2  Script::call(_object*, _object*, char const*, bool) (pFunction=0x1d1f1de8, 
pArgs=0x300dd440, errorPrefix=0x884bca "", okIfFunctionNull=) at 
/home/smj/original/bwengine/src/lib/pyscript/script.ipp:25

now I know that in _PyObject_GC_UNTRACK, 
(gdb) x/40x  op
0x1d1f1da8: 0x6d0x6f0x6e0x5f0x730x650x720x76
0x1d1f1db0: 0x650x720x2f0x720x750x6e0x5f0x73
0x1d1f1db8: 0x630x720x690x700x740x2e0x700x79
0x1d1f1dc0: 0x000x000x000x000x000x000x000x00
0x1d1f1dc8: 0x000x000x000x000x000x000x000x00
->  mov  -0x20(%rdi),%rax-> %rax = 0
0x1d1f1dd0: 0xf80x4d0xc50x2a0x000x000x000x00
->  mov  -0x18(%rdi),%rdx-> %rdx = 0x2ac54df8
0x1d1f1dd8: 0xfe0xff0xff0xff0xff0xff0xff0xff
0x1d1f1de0: 0xff0xff0xff0xff0xff0xff0xff0xff
0x1d1f1de8: 0x000x000x000x000x000x000x000x00
 <--PyFunctionObject  ob_refcnt 0 %rdi
0x1d1f1df0: 0x000xff0xba0x000x000x000x000x00
-> _typeobject* -> name function
0x1d1f1df8: 0x300x1e0x780x210x000x000x000x00
0x1d1f1e00: 0x280xaa0xba0x240x000x000x000x00
0x1d1f1e08: 0x100x530xfb0x2f0x000x000x000x00

When corruption,
the ob_refcnt is 0, the gc_refs is _PyGC_REFS_UNTRACKED, the gc_next is NULL 
but gc_prev is not.

How can it be? Is there some unknown bug in GC?

--
components: Interpreter Core
messages: 297696
nosy: 盛茂家
priority: normal
severity: normal
status: open
title: _PyObject_GC_UNTRACK corruption when call a lambda function with C API
type: crash
versions: Python 2.7

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue30852>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27673] lambda function in loop

2016-08-03 Thread Stefan Rosewig

Stefan Rosewig added the comment:

@Emanuel Barry
thanks for clarification, I didn't find this when I was searching for.

regards

Stefan

--

___
Python tracker 

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



[issue27673] lambda function in loop

2016-08-03 Thread Emanuel Barry

Emanuel Barry added the comment:

This is due to how closures work in Python: they only look up the value of the 
variable when the function is executed, not when it is created.

See the FAQ for more information and how to work around this: 
https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result

--
components:  -Tkinter
nosy: +ebarry
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

___
Python tracker 

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



[issue27673] lambda function in loop

2016-08-03 Thread Stefan Rosewig

New submission from Stefan Rosewig:

Trying to build tkinter menu dynamically by reading an ini file (configparser) 
I detect an issue with the lambda function used inside a loop. 
If the loop variable is used as option in the lambda function, the lambda is 
not place in time using the current value, all functions are created when 
leaving the calling function using the last value of the loop variable. 
There is a simple workaround, just use a separate function to add the 
menu-item. 
The attached demo shows both, the "Working" menu which was created by a 
function and does what was expected and the "Failure" menu which was created 
inside the loop itself and doesn't do what was expected.
Since the problem is not bound to configparser I used a simple loop walking 
through a list of menu item names to simulate the reasing of an ini file. 
Inside the loop a menu item with the name is appende to the Failure menu 
calling lambda:cmd(name) as command. Also a function is called uding the name 
as parameter wich appends a Menu item to the Working menu using the identic 
options as for Failure menu.
When the loop is finidhed the value of teh loop variable is set to "senseless" 
which should have no effect.
The function cmd(param) just appends a string including the param value to the 
output.
if the script is started the menus ar built and look identical but if you click 
on a Working menu item the name of the item is printed. if you click on the 
Failure menu item "senseless" is printed for each item which is the value I set 
after the loop.

>From my point of view all lambda commands are build when the calling function 
>is left using the value of the variable at this time. this lead in the demo  
>attached to identic function calls for the Failure menu. For the working menu 
>a separate function is called and the lambda is build at the end of this 
>function which leads to the expected behaviour.

I'm running Python 3.5.2 (v3.5.2:4def2a2901a5) 64 Bit on Windows-10 Pro 64

--
components: Tkinter
files: lambda-prob.pyw
messages: 271897
nosy: Thaloss66
priority: normal
severity: normal
status: open
title: lambda function in loop
type: behavior
versions: Python 3.5
Added file: http://bugs.python.org/file43989/lambda-prob.pyw

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue27673>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Could you explain lambda function to me?

2015-06-02 Thread Chris Kaynor
On Tue, Jun 2, 2015 at 11:14 AM, fl rxjw...@gmail.com wrote:

 Hi,

 I see the description of lambda at the online tutorial, but I cannot
 understand it. '42' is transferred to the function. What 'x' value should
 be? I do not see it says that it is '0'. And, what is 'x'?


The lambda keyword is merely another way to define a function.

As a general (and somewhat simplified rule),
func = lambda 1: 2
is the same as
def func(1):
return 2

The main difference is that lambda is an expression, while def is a
statement, which means you can use lambda is many places you cannot use
def, without adding extra lines of code.

 def make_incrementor(n):
 ... return lambda x: x + n
 ...
  f = make_incrementor(42)
  f(0)
 42
  f(1)
 43


Following the above rule, you can convert make_incrementor to look like:

def make_incrementor(n):
def func(x):
return x+n
return func

That function, when called, will return a new function that takes one
argument, and adds it to the argument to make_incrementor.

n will be assigned what ever is passed into make_incrementor (42 in the
example code), and x will be what ever is passed into the returned function
(0 and 1 in the example).


 The second lambda example is even more obscure to me:

  pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
  pairs.sort(key=lambda pair: pair[1])
  pairs
 [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


 Could you explain 'key=lambda pair: pair[1]' to me?


In this case, you are passing a new key function into list.sort. Per the
documentation [1], the key function will be given each item in the input
list and should return the key to sort that item by. The lambda is defining
a function which takes one of those items (named pair inside the function),
and returns the second item (index 1) of it. list.sort then sorts the items
in the original list based on this key, whereby you get four, one,
three, two sorted as strings, but the output will include the full
pairs.

This example could be rewritten as (again, following the general rule
mentioned at the top)
 def keyFunc(pair):
 return pair[1]
 pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
 pairs.sort(key=keyFunc)
 pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

[1] https://docs.python.org/2/howto/sorting.html#key-functions


 Python grammar seems too succinct to me.


 Thanks,

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain lambda function to me?

2015-06-02 Thread ast


fl rxjw...@gmail.com a écrit dans le message de 
news:323866d1-b117-4785-ae24-7d04c49bc...@googlegroups.com...

Hi,


def make_incrementor(n):

... return lambda x: x + n
...

f = make_incrementor(42)
f(0)

42

f(1)

43


make_incrementor is a fonction which return a function !
and the returned function just add n to its input

it is equivalent to:

def make_incrementor(n):

   def inc(x):
   return x+n

   return inc




The second lambda example is even more obscure to me:


pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs

[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


Could you explain 'key=lambda pair: pair[1]' to me?


the sort is done on the values returned by the key function
key function lambda pair: pair[1] returns the second element of each pair ( , 
)

so the sort is done alphabetically on the strings 'one' 'two' 'three' 'four'


--
https://mail.python.org/mailman/listinfo/python-list


Could you explain lambda function to me?

2015-06-02 Thread fl
Hi,

I see the description of lambda at the online tutorial, but I cannot 
understand it. '42' is transferred to the function. What 'x' value should
be? I do not see it says that it is '0'. And, what is 'x'?








 def make_incrementor(n):
... return lambda x: x + n
...
 f = make_incrementor(42)
 f(0)
42
 f(1)
43


The second lambda example is even more obscure to me:

 pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
 pairs.sort(key=lambda pair: pair[1])
 pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


Could you explain 'key=lambda pair: pair[1]' to me?

Python grammar seems too succinct to me.


Thanks,
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue23192] Generator return value ignored in lambda function

2015-03-12 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

Committed with non-dis test. Thank you for your contribution Bruno.

--
resolution:  - fixed
stage: test needed - resolved
status: open - closed

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



[issue23192] Generator return value ignored in lambda function

2015-03-11 Thread Roundup Robot

Roundup Robot added the comment:

New changeset 2b4a04c3681b by Serhiy Storchaka in branch '3.4':
Issue #23192: Fixed generator lambdas.  Patch by Bruno Cauet.
https://hg.python.org/cpython/rev/2b4a04c3681b

New changeset a3b889e9d3f3 by Serhiy Storchaka in branch 'default':
Issue #23192: Fixed generator lambdas.  Patch by Bruno Cauet.
https://hg.python.org/cpython/rev/a3b889e9d3f3

--
nosy: +python-dev

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



[issue23192] Generator return value ignored in lambda function

2015-03-11 Thread Bruno Cauet

Bruno Cauet added the comment:

Here is a working test, testing yield by lambda  function as well as lambda 
and function yielding from those.

--
Added file: 
http://bugs.python.org/file38440/0001-Add-tests-for-issue-23192.patch

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



[issue23192] Generator return value ignored in lambda function

2015-03-10 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

Could you please add a test based on Chris's example? And it would be good to 
add a test for a lambda with yield from.

--
assignee:  - serhiy.storchaka
stage:  - test needed

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



[issue23192] Generator return value ignored in lambda function

2015-03-02 Thread Ezio Melotti

Changes by Ezio Melotti ezio.melo...@gmail.com:


--
nosy: +ezio.melotti

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



[issue23192] Generator return value ignored in lambda function

2015-03-02 Thread Bruno Cauet

Bruno Cauet added the comment:

Here are the operations being emitted (line, macro used and eventual argument):

 f = lambda: (yield 5)
3487: ADDOP_O LOAD_CONST e-v.Num.n
3472: ADDOP YIELD_VALUE
1907: ADDOP_IN_SCOPE POP_TOP
4349: ADDOP_O LOAD_CONST Py_None
4350: ADDOP RETURN_VALUE
1457: ADDOP_O LOAD_CONST (PyObject*)co
1458: ADDOP_O LOAD_CONST qualname
1459: ADDOP_I MAKE_FUNCTION args
4349: ADDOP_O LOAD_CONST Py_None
4350: ADDOP RETURN_VALUE
 def g(): return (yield 5)
... 
3487: ADDOP_O LOAD_CONST e-v.Num.n
3472: ADDOP YIELD_VALUE
2533: ADDOP RETURN_VALUE
1457: ADDOP_O LOAD_CONST (PyObject*)co
1458: ADDOP_O LOAD_CONST qualname
1459: ADDOP_I MAKE_FUNCTION args
4349: ADDOP_O LOAD_CONST Py_None
4350: ADDOP RETURN_VALUE

So there's an extra POP_TOP + LOAD_CONST Py_NONE for the lambda version that 
throws away the 123 (in the exemple).

The attached patch (0001-...) fixes it. However please note that I'm not 
knowledgable about that part of the code and devised the patch empirically.
Moreover a test should probably added but I did not know where (test_dis? tried 
and failed... see patch 0002-...).

--
keywords: +patch
nosy: +bru
Added file: 
http://bugs.python.org/file38298/0001-lambda-generators-don-t-throw-away-stack-top.patch

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



[issue23192] Generator return value ignored in lambda function

2015-03-02 Thread Bruno Cauet

Changes by Bruno Cauet brunoca...@gmail.com:


Added file: 
http://bugs.python.org/file38299/0002-lambda-generator-fix-try-to-add-a-dis-test.patch

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



[issue23192] Generator return value ignored in lambda function

2015-01-08 Thread Chris Angelico

Chris Angelico added the comment:

I'm not sure what to look for in the code generation. In compile.c lines 3456 
and following, there's a LOAD_CONST None coming through, in the else branch of 
if (e-v.Yield.value), but nothing talking about lambda functions. There are 
constants COMPILER_SCOPE_LAMBDA and COMPILER_SCOPE_FUNCTION, but the only place 
where they're used is compiler_set_qualname() and I can't see anything obvious 
there. Hopefully someone more familiar with the code internals will be able to 
figure this out!

--

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



[issue23192] Generator return value ignored in lambda function

2015-01-08 Thread Serhiy Storchaka

Changes by Serhiy Storchaka storch...@gmail.com:


--
nosy: +benjamin.peterson, gvanrossum, serhiy.storchaka

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



[issue23192] Generator return value ignored in lambda function

2015-01-08 Thread Chris Angelico

Changes by Chris Angelico ros...@gmail.com:


--
type:  - behavior

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



[issue23192] Generator return value ignored in lambda function

2015-01-08 Thread Chris Angelico

New submission from Chris Angelico:

As yield is an expression, it's legal in a lambda function, which then
means you have a generator function. But it's not quite the same as
the equivalent function made with def:

$ python3
Python 3.5.0a0 (default:1c51f1650c42+, Dec 29 2014, 02:29:06)
[GCC 4.7.2] on linux
Type help, copyright, credits or license for more information.
 f=lambda: (yield 5)
 x=f()
 next(x)
5
 x.send(123)
Traceback (most recent call last):
  File stdin, line 1, in module
StopIteration
 def f(): return (yield 5)
...
 x=f()
 next(x)
5
 x.send(123)
Traceback (most recent call last):
  File stdin, line 1, in module
StopIteration: 123
 x = (lambda: print((yield 1)) or 2)()
 next(x)
1
 x.send(3)
3
Traceback (most recent call last):
  File stdin, line 1, in module
StopIteration

The last example demonstrates that send() is working, but the return value is 
not getting propagated. Disassembly shows this:

 dis.dis(lambda: (yield 5))
  1   0 LOAD_CONST   1 (5)
  3 YIELD_VALUE
  4 POP_TOP
  5 LOAD_CONST   0 (None)
  8 RETURN_VALUE
 def f(): return (yield 5)
... 
 dis.dis(f)
  1   0 LOAD_CONST   1 (5)
  3 YIELD_VALUE
  4 RETURN_VALUE

I'm sure this is a bug that will affect very approximately zero people, but 
it's still a peculiar inconsistency!

Verified with 3.5 and 3.4.

--
components: Interpreter Core
messages: 233662
nosy: Rosuav
priority: normal
severity: normal
status: open
title: Generator return value ignored in lambda function
versions: Python 3.4, Python 3.5

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



[issue23192] Generator return value ignored in lambda function

2015-01-08 Thread STINNER Victor

Changes by STINNER Victor victor.stin...@gmail.com:


--
nosy: +haypo

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



[issue23192] Generator return value ignored in lambda function

2015-01-08 Thread Guido van Rossum

Guido van Rossum added the comment:

Hm, looks like nobody bothered to update the lambda code generation to use the 
value from yield. I almost feel like there is some unnecessary check if we are 
in a lambda in the code generation for yield. Have you looked through the code 
generation yet?

--

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



Re: Lambda function Turing completeness

2013-08-24 Thread Piet van Oostrum
Musical Notation musicdenotat...@gmail.com writes:

 Is it possible to write a Turing-complete lambda function (which does
 not depend on named functions) in Python?

The wording of this question is questionable. Turing completeness is not
an attribute of a function, but of a system (for example a programming
language or a machine). It means that for every Turing machine you can
write a program in that language or program the machine in such a way
that it emulates that Turing machine.

So you could ask if the subset of the Python programs consisting only of
a lambda expression is Turing complete. Or alternatively if for every
Turing machine you can write a lambda expression that emulates that
Turing machine.

It has been proven that the λ calculus is equivalent to Turing machines,
so if the lambda calculus can be emulated with Python's lambda
expressions the answer is yes. In the lambda calculus you can define
lambda expressions and apply functions to parameters. The parameters may
be functions (in fact in the pure λ calculus there is nothing else), so
functions must be first class citizens. Fortunately in Python this is
the case. So we suspect it can be done.

An important result in the λ calculus is that every expression can be
expressed in three functions S, K and I with only function application.
So we are going to try to do these in Python and see if it works.

The definitions in the λ calculus are:

S = λ x y z. (x z) (y z)
K = λ x y. x
I = λ x. x

The dot is used where Python uses :, function application is written as
juxtaposition: f x and λ x y is an abbreviation of λ x. λ y

So we are going to translate these in python. We have to explicitely
write the lambda's (each one with a single parameter) and add
parentheses around the function arguments if not already there.

 S = lambda x: lambda y: lambda z: x(z) (y(z))
 K = lambda x: lambda y: x
 I = lambda x: x

Now there is a theorem that SKK == I (I is the identity), so we are
going to test that:

 S(K)(K)('test')
'test'

a few more tests:

 for x in range(100):
... if S(K)(K)(x) != I(x):
... print('Not equal for x = %s' % x)
... 

All seem to be equal.

Of course we still have used names for the functions, but this is not
essential. We can just replace each of S, K, and I with their
definition:

 print((lambda x: lambda y: lambda z: x(z) (y(z))) # S
... (lambda x: lambda y: x)   # (K)
...   (lambda x: lambda y: x)('test'))# (K) ('test')
test

 for x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
... if ((lambda x: lambda y: lambda z: x(z) (y(z)))
... (lambda x: lambda y: x)
... (lambda x: lambda y: x)(x)) != (lambda x: x)(x):
...   print('Not equal for x = %s' % x)
... 
Success!

Now the pure λ lambda calculus has to express inter=gers, booleans etc.
also as lambda expressions and this makes it really unwieldy. However,
you can add some standard functions or expressions for these and that
doesn't diminish the expressiveness of the calculus. So I suppose that
you want to allow the use of all standard Python functions and
expressions.

Modern Pythons have conditional expressions, so this helps. We don't
have to emulate booleans and conditions with weird lambda expressions.
In Python's lambda expressions you can not use statements, only
expressions, so without conditional expressiosn Python's booleans
wouldn't be very useful.

The remaining problem is how to use loops or recursion. I'll do that in
a separate posting.
-- 
Piet van Oostrum p...@vanoostrum.org
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda function Turing completeness

2013-08-24 Thread Piet van Oostrum
This is the second part of my posting on the Turing completeness of
Python's lambda expressions. This time I am going to define a recursive
function as a lambda expression (I use lambda when I am talking about
Python's lambda expressions, and λ for the theory – λ calculus.)

Now of course it is easy to define a recursive function if you can use
its function name inside the body. But the question of the OP was if you
can do it without named functions. The pure λ calculus only works with
unnamed λ expressions. Therefore we need a special operator to define
recursive functions. This is the so called Y combinator, or Y
operator[1].

The defining characteristic of Y is:

Y(f)  = f(Y(f)) for all functions f.
 
There are several possible definitions of this operator, but some of
them work only for programming languages with lazy evaluation or call by
name. For Python's call by valye the following one will work:

Y = λf.(λx.f (λv.((x x) v))) (λx.f (λv.((x x) v)))

Translated in Python:

 Y = lambda f: (lambda x: f (lambda v: ((x (x)) (v \
... (lambda x: f (lambda v: ((x (x)) (v

We are going to define a lambda expression for the factorial function.
We need a helper function for this. The idea is to have the final
recursive function as a parameter of the helper function. See [1].

def fact_helper(f, n):
if n == 0:
return 1
else:
return n * f(n-1)

No we have to rewrite this to get a proper lambda expression. We split
the two parameters and give each of them a lambda, and we replace the if
statement with a conditional expression.

 fact_helper = lambda f: lambda n: (1 if n == 0 else n * f(n-1))

Now we apply the Y combinator to fact_helper to get the recursive fact
function and check it:

 fact = Y (fact_helper)
 fact(5)
120

Of course to get pure we have to get rid of the names of the functions.
So we replace each of Y, fact and fact_helper with their definition:

 (lambda f: (lambda x: f (lambda v: ((x (x)) (v \
...(lambda x: f (lambda v: ((x (x)) (v) \
...(lambda f: lambda n: (1 if n == 0 else n * f(n-1))) (5)
120

Lo and behold! We have the right answer.

Now writing a universal Turing machine as a single Python lambda
expression is left as an exercise for the reader.

BTW. If you use Python 3 you can have print inside a lambda expression,
so this makes all this even nicer.
--
[1] http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator
-- 
Piet van Oostrum p...@vanoostrum.org
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda function Turing completeness

2013-08-01 Thread Steven D'Aprano
On Wed, 31 Jul 2013 13:53:26 +0700, Musical Notation wrote:

 Is it possible to write a Turing-complete lambda function (which does
 not depend on named functions) in Python?


lambda s: eval(s)



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda function Turing completeness

2013-08-01 Thread Ian Kelly
On Wed, Jul 31, 2013 at 11:55 PM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Wed, 31 Jul 2013 13:53:26 +0700, Musical Notation wrote:

 Is it possible to write a Turing-complete lambda function (which does
 not depend on named functions) in Python?


 lambda s: eval(s)

eval is a named function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Lambda function Turing completeness

2013-07-31 Thread Musical Notation
Is it possible to write a Turing-complete lambda function (which does not 
depend on named functions) in Python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda function Turing completeness

2013-07-31 Thread Schneider

On Wed 31 Jul 2013 08:53:26 AM CEST, Musical Notation wrote:

Is it possible to write a Turing-complete lambda function (which does not 
depend on named functions) in Python?


what should a sinlge Turing-complete lambda function be?
For me, a programming language can be Turing-complete or a function can 
be universal,  e.g. like an interpreter for a  programming language.


bg,
Johannes

--
GLOBE Development GmbH
Königsberger Strasse 260
48157 MünsterGLOBE Development GmbH
Königsberger Strasse 260
48157 Münster
0251/5205 390
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda function Turing completeness

2013-07-31 Thread Ian Kelly
On Wed, Jul 31, 2013 at 12:53 AM, Musical Notation
musicdenotat...@gmail.com wrote:
 Is it possible to write a Turing-complete lambda function (which does not 
 depend on named functions) in Python?

Yes, lambda functions are Turing-complete.  You can get anonymous
recursion by defining the function to take a recursive function
argument and then passing it to itself.  For example, this will
(inefficiently) give you the 13th Fibonacci number:

(lambda f, n: f(f, n))(lambda f, n: n if n  2 else f(f, n-2) + f(f, n-1), 13)
-- 
http://mail.python.org/mailman/listinfo/python-list


[issue15692] Unexpected exponentiation in lambda function

2012-08-16 Thread Björn Dahlgren

New submission from Björn Dahlgren:

Hi, I hope this is not a false positive but I cannot help thinking this is a 
bug, consider:

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type help, copyright, credits or license for more information.
 -3.2**0
-1.0
 sign=lambda x: x**0
 sign(-3.2)
1.0

Python 3.2.3 (default, May  3 2012, 15:51:42) 
[GCC 4.6.3] on linux2
Type help, copyright, credits or license for more information.
 -3.2**0
-1.0
 sign=lambda x: x**0
 sign(-3.2)
1.0


Or is this expected?

Best regards,
Björn Dahlgren

--
components: None
messages: 168384
nosy: bjodah
priority: normal
severity: normal
status: open
title: Unexpected exponentiation in lambda function
versions: Python 2.7, Python 3.2

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue15692
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue15692] Unexpected exponentiation in lambda function

2012-08-16 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

-3.2**0 == -(3.2**0)

 (-3.2)**0
1.0

--
nosy: +storchaka
resolution:  - invalid
status: open - closed

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue15692
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



How to pickle a lambda function?

2009-08-11 Thread Terry
Hi,

I'm trying to implement something like:

remote_map(fun, list)

to execute the function on a remove machine. But the problem is I
cannot pickle a lambda function and send it to the remote machine.

Is there any possible way to pickle (or other method) any functions
including lambda?

br, Terry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to pickle a lambda function?

2009-08-11 Thread Duncan Booth
Terry terry.yin...@gmail.com wrote:

 I'm trying to implement something like:
 
 remote_map(fun, list)
 
 to execute the function on a remove machine. But the problem is I
 cannot pickle a lambda function and send it to the remote machine.
 
 Is there any possible way to pickle (or other method) any functions
 including lambda?
 

You can pickle any named functions that are declared at module scope.

You cannot pickle anonymous functions, methods, or functions declared 
nested inside other functions. The function must be present in the same 
module when you unpickle it, and if the definition has changed between 
pickling and unpickling the new definition will be used (just as other 
instances will use the current class definition not the one they were 
pickled with).

You probably could pickle some of the components needed to create your 
lambda and construct a new function from it when unpickling: try the code 
object, the name of the module to be used for the globals, and default 
arguments. I don't think you can pickle the closure so better make sure 
your lambda doesn't need one, and be very careful to ensure that you 
restore the pickle in the same version of Python otherwise the code object 
might break. Best just avoid this and use named functions for anything that 
needs pickling.

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to pickle a lambda function?

2009-08-11 Thread Terry
On Aug 11, 3:42 pm, Duncan Booth duncan.bo...@invalid.invalid wrote:
 Terry terry.yin...@gmail.com wrote:
  I'm trying to implement something like:

  remote_map(fun, list)

  to execute the function on a remove machine. But the problem is I
  cannot pickle a lambda function and send it to the remote machine.

  Is there any possible way to pickle (or other method) any functions
  including lambda?

 You can pickle any named functions that are declared at module scope.

 You cannot pickle anonymous functions, methods, or functions declared
 nested inside other functions. The function must be present in the same
 module when you unpickle it, and if the definition has changed between
 pickling and unpickling the new definition will be used (just as other
 instances will use the current class definition not the one they were
 pickled with).

 You probably could pickle some of the components needed to create your
 lambda and construct a new function from it when unpickling: try the code
 object, the name of the module to be used for the globals, and default
 arguments. I don't think you can pickle the closure so better make sure
 your lambda doesn't need one, and be very careful to ensure that you
 restore the pickle in the same version of Python otherwise the code object
 might break. Best just avoid this and use named functions for anything that
 needs pickling.

 --
 Duncan Boothhttp://kupuguy.blogspot.com

Yes, I'm think of pickle (actually marshal) the code object. Otherwise
I have to use string and eval:-(

The reason I need to be able to pickle any function is because I want
my remote machine knows nothing about the function before receiving
it, so I don't need to update the source code in the remote machine
very often.

br, terry
-- 
http://mail.python.org/mailman/listinfo/python-list


Lambda function

2009-02-25 Thread aditya saurabh
I defined two functions - lets say
fa = lambda x: 2*x
fb = lambda x: 3*x
Now I would like to use fa*fb in terms of x
is there a way?
Thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda function

2009-02-25 Thread Albert Hopkins
On Wed, 2009-02-25 at 17:56 +0530, aditya saurabh wrote:
 I defined two functions - lets say
 fa = lambda x: 2*x
 fb = lambda x: 3*x
 Now I would like to use fa*fb in terms of x
 is there a way?
 Thanks in advance

I'm not sure what use fa*fb in terms of x means.

But if you mean fa(x) * fb(x) then it's just:

fa(x) * fb(x)

-a

--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda function

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 12:42:32 -0200, Albert Hopkins  
mar...@letterboxes.org escribió:

On Wed, 2009-02-25 at 17:56 +0530, aditya saurabh wrote:



I defined two functions - lets say
fa = lambda x: 2*x
fb = lambda x: 3*x
Now I would like to use fa*fb in terms of x
is there a way?
Thanks in advance


I'm not sure what use fa*fb in terms of x means.

But if you mean fa(x) * fb(x) then it's just:

fa(x) * fb(x)


I think he wants function composition, fb(fa(x)):

def compose(*funcs):
  def composed(x, funcs=funcs):
for f in reversed(funcs):
  x = f(x)
return x
  return composed

def square(x): return x**2
def plus1(x): return x+1
# same as plus1 = lambda x: x+1 but I like the def syntax

y = compose(square, plus1) # y=(x+1)**2
y(3) # - 16

(or is it fa(fb(x))?)

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list


dynimac code with lambda function creation

2008-03-27 Thread Justin Delegard
So I am trying to pass an object's method call to a function that 
requires a function pointer.  I figured an easy way to do it would be to 
create a lambda function that calls the correct method, but this is 
proving more difficult than I imagined.

Here is the function I'm using:

def objectMethodCallerFunctionCreator(testerObj, method):
exec(y=lambda x: testerObj.+method+(x))
return y


Where testerObj is an instance of an object, and method is a string 
representing the method to call.  The problem is, when I actually run 
the function created (y in this case), it tells me it can't find the 
symbol testerObj in the global scope.  I have successfully created 
similar functions, except without using the exec() call. e.g.

def functionCreator(a, b, c):
return lambda d: myFunc(a, b, c, d)

and it doesn't complain about the variables a, b, or c when being run.  
I am assuming this is happening because of the exec() call, but I don't 
see another way of calling a variable method on an object.  Is there 
some other way to do this that I'm missing?  I tried passing in 'method' 
as a function pointer (to the method of the object), but that didn't 
work either.

Thanks,
Justin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynimac code with lambda function creation

2008-03-27 Thread Laszlo Nagy
Justin Delegard wrote:
 So I am trying to pass an object's method call to a function that 
 requires a function pointer.  I figured an easy way to do it would be to 
 create a lambda function that calls the correct method, but this is 
 proving more difficult than I imagined.

 Here is the function I'm using:

 def objectMethodCallerFunctionCreator(testerObj, method):
 exec(y=lambda x: testerObj.+method+(x))
 return y
   
You are making it too difficult. What about this:

def objectMethodCallerFunctionCreator(testerObj, method):
return getattr(testerObj,method)

BTW, when you need to return a value (instead of simple code execution) you 
should use eval() instead of exec().

 Where testerObj is an instance of an object, and method is a string 
 representing the method to call.  The problem is, when I actually run 
 the function created (y in this case), it tells me it can't find the 
 symbol testerObj in the global scope.  
That is true. The 'testerObj' parameter is assigned to the local 
namespace. The local namespace is created when the function is called. 
When you call exec, it creates a new namespace. Thus, testerObj is not 
available inside exec(). But please see above - you do not need exec for 
this. It is unsafe, slow and really not necessary.

 I am assuming this is happening because of the exec() call, but I don't 
 see another way of calling a variable method on an object.  
Generally, you should not use exec, eval and their counterparts to 
access certain attributes of different objects. Same for defining 
functions, classes, create instances etc.

If you still feel that you need to use eval or exec for some reason, 
drop me an email and hopefully I can help avoiding it. :-)

Best,

   Laszlo

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynimac code with lambda function creation

2008-03-27 Thread Bruno Desthuilliers
Justin Delegard a écrit :
 So I am trying to pass an object's method call

I assume you mean to pass an object's method, since I don't get what 
passing an object's method call could mean.

 to a function that 
 requires a function pointer. 

s/pointer/object/

There's nothing like a pointer in Python, and Python's functions are 
plain objects (instances of class 'function'). FWIW and WWAI, Python's 
methods are thin callable wrappers around the function, the class and 
(for bound methods) the instance.

 I figured an easy way to do it would be to 
 create a lambda function that calls the correct method, but this is 
 proving more difficult than I imagined.

easy ???

Here's the easy way to pass a method to a function:

def func(method):
   return method(42)

class MyClass(object):
   def __init__(self, name):
 self.name = name

   def foo(self, whatever):
  return I'm %s and whatever is %s % (self.name, str(whatever))


obj = MyClass('boo')
print func(obj.foo)


 Here is the function I'm using:
 
 def objectMethodCallerFunctionCreator(testerObj, method):
exec(y=lambda x: testerObj.+method+(x))
return y

My my my... Looks like you're in for the Rube Goldberg Award !-)

Whenever you think exec (or eval FWIW) is the solution, odds are there's 
a way better solution.

If what you want is to retrieve a reference to an attribute you only 
know by it's name, getattr() is your friend. And in Python, methods are 
attributes.

def objectMethodCallerFunctionCreator(testerObj, method):
  y = lambda x: getattr(testerObj, method)(x)
  return y

But as we've seen above, all this is useless overcomplexification. Just 
pass the method like it was any other attribute, and you're done.

 
 Where testerObj is an instance of an object, and method is a string 
 representing the method to call.  The problem is, when I actually run 
 the function created (y in this case), it tells me it can't find the 
 symbol testerObj in the global scope.

This is related to exec as far as I can tell.

  I have successfully created 
 similar functions, except without using the exec() call. e.g.
 
 def functionCreator(a, b, c):
return lambda d: myFunc(a, b, c, d)
 
 and it doesn't complain about the variables a, b, or c when being run.  
 I am assuming this is happening because of the exec() call, but I don't 
 see another way of calling a variable method on an object.   Is there
 some other way to do this that I'm missing? 

print func(getattr(obj, 'foo'))

 I tried passing in 'method' 
 as a function pointer (to the method of the object), but that didn't 
 work either.

What did you try, and what result did you get ? 'does not work' is 
(almost) the most useless description of a problem.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynimac code with lambda function creation

2008-03-27 Thread Justin Delegard




It didn't work when I tried to pass the method object, because 'self'
wasn't being recognized as a valid symbol. I've just been breaking my
teeth on python OO, so I didn't realize that 'self' needed to be the
first argument of every method that used it. After inserting that,
everything worked fine when I pass just the method object!

Thanks all.
Justin

Bruno Desthuilliers wrote:

  Justin Delegard a crit :
  
  
So I am trying to pass an object's method call

  
  
I assume you mean "to pass an object's method", since I don't get what 
passing "an object's method call" could mean.

  
  
to a function that 
requires a function pointer. 

  
  
s/pointer/object/

There's nothing like a pointer in Python, and Python's functions are 
plain objects (instances of class 'function'). FWIW and WWAI, Python's 
methods are thin callable wrappers around the function, the class and 
(for bound methods) the instance.

  
  
I figured an easy way to do it would be to 
create a lambda function that calls the correct method, but this is 
proving more difficult than I imagined.

  
  
"easy" ???

Here's the easy way to pass a method to a function:

def func(method):
   return method(42)

class MyClass(object):
   def __init__(self, name):
 self.name = name

   def foo(self, whatever):
  return "I'm %s and whatever is %s" % (self.name, str(whatever))


obj = MyClass('boo')
print func(obj.foo)


  
  
Here is the function I'm using:

def objectMethodCallerFunctionCreator(testerObj, method):
   exec("y=lambda x: testerObj."+method+"(x)")
   return y

  
  
My my my... Looks like you're in for the Rube Goldberg Award !-)

Whenever you think exec (or eval FWIW) is the solution, odds are there's 
a way better solution.

If what you want is to retrieve a reference to an attribute you only 
know by it's name, getattr() is your friend. And in Python, methods are 
attributes.

def objectMethodCallerFunctionCreator(testerObj, method):
  y = lambda x: getattr(testerObj, method)(x)
  return y

But as we've seen above, all this is useless overcomplexification. Just 
pass the method like it was any other attribute, and you're done.

  
  
Where testerObj is an instance of an object, and method is a string 
representing the method to call.  The problem is, when I actually run 
the function created (y in this case), it tells me it can't find the 
symbol testerObj in the global scope.

  
  
This is related to exec as far as I can tell.

  
  
 I have successfully created 
similar functions, except without using the exec() call. e.g.

def functionCreator(a, b, c):
   return lambda d: myFunc(a, b, c, d)

and it doesn't complain about the variables a, b, or c when being run.  
I am assuming this is happening because of the exec() call, but I don't 
see another way of calling a variable method on an object.   Is there
some other way to do this that I'm missing? 

  
  
print func(getattr(obj, 'foo'))

  
  
I tried passing in 'method' 
as a function pointer (to the method of the object), but that didn't 
work either.

  
  
What did you try, and what result did you get ? 'does not work' is 
(almost) the most useless description of a problem.

  




-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Is this a bug of the lambda function

2007-10-12 Thread Carsten Haese
On Fri, 12 Oct 2007 01:00:47 -0400, Zhu Wayne wrote 
 Hi, 
 I have a short code which gives me strange results, the code is as follows: 
 
 f = [lambda x: None]*5 
 for j in range(0, 5): 
  f[j] = lambda x: float(j)*x 
 [...]
 It seems only when I use the index j (which is declear with the lambda
 function), I can get expected answer [...]

'j' is not declared with the lambda function. Inside the lambda, 'j' is a
global name. Global names inside a function body are looked up when the
function is called, not when the function is defined.

You are actually defining five identical functions that look up the global
name j, take its float value, and multiply that times the argument x.
If the name 'j' is deleted, the functions won't run anymore. Observe:

 f = [lambda x: None]*5
 for j in range(0, 5):
...   f[j] = lambda x: float(j)*x
...
 del j
 f[0](1)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 2, in lambda
NameError: global name 'j' is not defined

To get the behavior you expect, you're going to have to cause the name 'j' to
be looked up (and frozen, so to speak) at the time the lambda is defined. One
way to do that is to use a default function argument:

 for j in range(0, 5):
...   f[j] = lambda x, inner_j=j: float(inner_j)*x
...
 del j
 f[0](1.)
0.0

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Is this a bug of the lambda function

2007-10-11 Thread Zhu Wayne
Hi,
I have a short code which gives me strange results, the code is as follows:

f = [lambda x: None]*5
for j in range(0, 5):
 f[j] = lambda x: float(j)*x
print print f[k](1.),
for k in range(5):
 print f[k](1.),
print expect 0. 1. 2. 3. 4.
print
print print f[j](1.),
for j in range(5):
 print f[j](1.),
print expect 0. 1. 2. 3. 4.
print
print print f[0](1.), f[1](1.), ...
print f[0](1.), f[1](1.), f[2](1.), f[3](1.), f[4](1.)
print expect 0. 1. 2. 3. 4.

*
The result is very strange:

print f[k](1.),
4.0 4.0 4.0 4.0 4.0 expect 0. 1. 2. 3. 4.

print f[j](1.),
0.0 1.0 2.0 3.0 4.0 expect 0. 1. 2. 3. 4.

print f[0](1.), f[1](1.), ...
4.0 4.0 4.0 4.0 4.0
expect 0. 1. 2. 3. 4.


It seems only when I use the index j (which is declear with the lambda
function), I can get expected answer, otherwise the result is not
unexpected.

Could anybody give me a possible explanation to this? Does python use kind
of pre-complie techinque to treat the lambda function? (like the macro in C
or inline function in C++)

Thanks in advance

Wayne
-- 
http://mail.python.org/mailman/listinfo/python-list

[ python-Bugs-1692280 ] lambda function segfault

2007-04-01 Thread SourceForge.net
Bugs item #1692280, was opened at 2007-04-01 18:05
Message generated for change (Settings changed) made by dasn
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1692280group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Interpreter Core
Group: Python 2.5
Status: Open
Resolution: None
Priority: 9
Private: No
Submitted By: Dasn (dasn)
Assigned to: Nobody/Anonymous (nobody)
Summary: lambda function segfault

Initial Comment:
 lambda ((x,y)): 'ok'
Segment fault (core dumped).

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1692280group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1692280 ] lambda function segfault

2007-04-01 Thread SourceForge.net
Bugs item #1692280, was opened at 2007-04-01 10:05
Message generated for change (Comment added) made by gbrandl
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1692280group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Interpreter Core
Group: Python 2.5
Status: Closed
Resolution: Out of Date
Priority: 9
Private: No
Submitted By: Dasn (dasn)
Assigned to: Nobody/Anonymous (nobody)
Summary: lambda function segfault

Initial Comment:
 lambda ((x,y)): 'ok'
Segment fault (core dumped).

--

Comment By: Georg Brandl (gbrandl)
Date: 2007-04-01 10:15

Message:
Logged In: YES 
user_id=849994
Originator: NO

Thanks, this is already fixed in SVN and will be part of 2.5.1, which is
scheduled to be released soon.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1692280group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com