Strange closure behaviour

Rémy Mouëza remy.moueza at gmail.com
Sun Jun 16 14:00:15 UTC 2019


On Sunday, 16 June 2019 at 01:36:38 UTC, Timon Gehr wrote:
> It's a bug. It's memory corruption. Different objects with 
> overlapping
>  lifetimes use the same memory location.
Okay. Seen that way, it is clear to me why it's a bug.

> ...
> No, it's not the same. Python has no sensible notion of 
> variable scope.
>
> >>> for i in range(3): pass
> ...
> >>> print(i)
> 2
>
> Yuck.

I got confused by this Python behavior:

ls = []
for i in range(0, 5):
    ls.append(lambda x: x + i)
for fun in ls:
    print(fun(0))

This prints:
4
4
4
4
4


More information about the Digitalmars-d-learn mailing list