Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Jussi Piitulainen Newsgroups: comp.lang.python Subject: Re: What does a list comprehension do Date: Thu, 26 Nov 2015 18:11:57 +0200 Organization: A noiseless patient Spider Lines: 65 Message-ID: References: <877fldnm9z.fsf@handshake.de> <87k2p4ex5x.fsf@elektro.pacujo.net> <87fuzseuee.fsf@elektro.pacujo.net> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="305c68510616a2e7ac08bcd2ff1598bd"; logging-data="16966"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX198wzkA1AtqHTSXNOLpqnV13o6lGzDScPg=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:MoP+6AaaXAU4z4IcHaK2qpn3kCs= sha1:TvIApn+AuuDEUwAw8a5n8nvTx8Y= Xref: csiph.com comp.lang.python:99586 Antoon Pardon writes: > Op 26-11-15 om 14:56 schreef Marko Rauhamaa: >> Antoon Pardon wrote: >> >>> I don't understand. What I propose would be a minor change in how >>> list comprehension works. I don't see how your example can be turned >>> into a list comprehension. >> >> The list comprehension is only a special case of the interaction >> between closures and variables. If you dabble with list >> comprehensions and lambdas, you'll need to make consistent changes in >> closure semantics. > > It would only dabble with the list comprehension not with the lambda. > The effect of the change would only be that a list comprehension like > > [ for in ] > > would implicitly be rewritten as follows: > > [ (lambda : )() for in ] > > There would no change on how lambdas work or functions or closures. > >> BTW, all(!?) other languages from Java to Scheme share closure semantics >> with Python so you would really be making a mess by changing Python. > > Not this proposal, which wouldn't touch closure semantics. It needs to take into account the possibility of more than one variable, but that's a minor adjustment. I like it. It's simple enough. The following code exercises different values from nested comprehension loops, together with a shared global whose value actually changes before each call to one of the listed thunks. m = "good morning to you" thoughts = [ (lambda n, u : ((lambda : (u//2)*m), (lambda : n))) (n, u) for n in range(10) if n % 2 # odd? for u in range(10) if u % 2 - 1 # less odd? if n < u ] for t, g in zip(thoughts, ((["hello"], ["eiku"], ["hej"]) + tuple(20 * "."))): m = g message, number = t print(number(), *message()) # Prints: 1 hello 1 eiku eiku 1 hej hej hej 1 . . . . 3 . . 3 . . . 3 . . . . 5 . . . 5 . . . . 7 . . . .