Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It's important to note that scoping on Python for loop variables does not behave the same way it does for a C# foreach.

While it's possible to write this in Python:

    for i in [1, 2, 3, 4]:
        pass
    final_value = i
The same in C# is not possible, i.e.:

    int[] values = {1, 2, 3, 4};
    foreach(int i in values) {
    }
    var final_value = i;       // there is no i here!
It makes no sense to "fix" this in Python because the loop variable is created in the scope outside of the for loop. It seems to make sense in the case of the C# foreach (but not the C# for!) because that variable is inaccessible outside of the foreach loop scope anyway. I would still argue introducing inconsistent behaviour between for and foreach as they are doing in C# 5 is just going to further obscure this problem and not really eliminate it.

Anyway, as far as Python is concerned, closures close over variables not values. Creating special cases where this is not the case is bound to generate even greater confusion.



Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: