[Python-ideas] 'Injecting' objects as function-local constants

Jan Kaliszewski zuo at chopin.edu.pl
Mon Jun 13 02:03:32 CEST 2011


Greg Ewing dixit (2011-06-13, 10:30):

> I'm -1 on any proposal that somehow tries to make the
> default-argument hack more acceptable.

My propositions don't make that hack less acceptable -- proposing an
alternative.

> The main reason people still feel the need to use it
> is that the for-loop is broken, insofar as it doesn't
> create a new binding for each iteration.
> 
> The right way to address that is to fix the for-loop,
> IMO.

Do you mean that each iteration should create separate local scope?
Then:

    j = 0
    my_lambdas = []
    for i in range(10):
        print(j)  # would raise UnboundLocalError
        j = i
        my_lambdas.append(lambda: i)

Or that the loop variable should be treated specially?
Then:

    i_lambdas, j_lambdas = [], []
    for i in range(10):
        j = i
        i_lambdas.append(lambda: i)
        j_lambdas.append(lambda: j)
    print(i_lambdas[2]())  # would print 2
    print(j_lambdas[2]())  # would print 9

Cheers.
*j




More information about the Python-ideas mailing list