473,624 Members | 2,269 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PEP-xxx: Unification of for statement and list-comp syntax

Hi all!

The following PEP tries to make the case for a slight unification of for
statement and list comprehension syntax.

Comments appreciated, including on the sample implementation.

===
PEP: xxx
Title: Unification of for-statement and list-comprehension syntax
Version: $Revision$
Last-Modified: $Date$
Author: Heiko Wundram <me@modelnine.o rg>
Status: Active
Type: Standards Track
Content-Type: text/plain
Created: 21-May-2006
Post-History: 21-May-2006 17:00 GMT+0200
Abstract

When list comprehensions were introduced, they added the ability
to add conditions which are tested before the expression which is
associated with the list comprehension is evaluated. This is
often used to create new lists which consist only of those items
of the original list which match the specified condition(s). For
example:

[node for node in tree if node.haschildre n()]

will create a new list which only contains those items of the
original list (tree) whose items match the havechildren()
condition. Generator expressions work similarily.

With a standard for-loop, this corresponds to adding a continue
statement testing for the negated expression at the beginning of
the loop body.

As I've noticed that I find myself typing the latter quite often
in code I write, it would only be sensible to add the corresponding
syntax for the for statement:

for node in tree if node.haschildre n():
<do something with node>

as syntactic sugar for:

for node in tree:
if not node.haschildre n():
continue
<do something with node>

There are several other methods (including generator-expressions or
list-comprehensions, the itertools module, or the builtin filter
function) to achieve this same goal, but all of them make the code
longer and harder to understand and/or require more memory, because
of the generation of an intermediate list.
Implementation details

The implementation of this feature requires changes to the Python
grammar, to allow for a variable number of 'if'-expressions before
the colon of a 'for'-statement:

for_stmt: 'for' exprlist 'in' testlist_safe ('if' old_test)* ':'
suite ['else' ':' suite]

This change would replace testlist with testlist_safe as the
'in'-expression of a for statement, in line with the definition of
list comprehensions in the Python grammar.

Each of the 'if'-expressions is evaluated in turn (if present), until
one is found False, in which case the 'for'-statement restarts at the
next item from the generator of the 'in'-expression immediately
(the tests are thus short-circuting), or until all are found to be
True (or there are no tests), in which case the suite body is executed.
The behaviour of the 'else'-suite is unchanged.

The intermediate code that is generated is modelled after the
byte-code that is generated for list comprehensions:

def f():
for x in range(10) if x == 1:
print x

would generate:

2 0 SETUP_LOOP 42 (to 45)
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (10)
9 CALL_FUNCTION 1
12 GET_ITER
13 FOR_ITER 28 (to 44) 16 STORE_FAST 0 (x)
19 LOAD_FAST 0 (x)
22 LOAD_CONST 2 (1)
25 COMPARE_OP 2 (==)
28 JUMP_IF_FALSE 9 (to 40)
31 POP_TOP

3 32 LOAD_FAST 0 (x)
35 PRINT_ITEM
36 PRINT_NEWLINE
37 JUMP_ABSOLUTE 13 40 POP_TOP 41 JUMP_ABSOLUTE 13 44 POP_BLOCK
45 LOAD_CONST 0 (None)

48 RETURN_VALUE

where all tests are inserted immediately at the beginning of the
loop body, and jump to a new block if found to be false which pops
the comparision from the stack and jumps back to the beginning of
the loop to fetch the next item.

Implementation issues

The changes are backwards-compatible, as they don't change the
default behaviour of the 'for'-loop. Also, as the changes that
this PEP proposes don't change the byte-code structure of the
interpreter, old byte-code continues to run on Python with this
addition unchanged.
Implementation

A sample implementation (with updates to the grammar documentation
and a small test case) is available at:
http://sourceforge.net/tracker/index...70&atid=305470
Copyright

This document has been placed in the public domain.
===

--- Heiko.
May 21 '06 #1
6 2159
i wanted to suggest this myself. +1
-tomer

May 21 '06 #2
KW
On 2006-05-21, Heiko Wundram wrote:
Hi all!

The following PEP tries to make the case for a slight unification of for
statement and list comprehension syntax.


Sounds great!

--
Konrad
May 21 '06 #3
Heiko Wundram wrote:
The following PEP tries to make the case for a slight unification of for
statement and list comprehension syntax.


-1

Adds complexity to the language and saves you nothing but an indent
level. However, I encourage you to submit this PEP and get a (almost
certianly negative) pronouncement, so we have it on the record.
Carl Banks

May 21 '06 #4
Heiko Wundram wrote:
....
As I've noticed that I find myself typing the latter quite often
in code I write, it would only be sensible to add the corresponding
syntax for the for statement:

for node in tree if node.haschildre n():
<do something with node>

as syntactic sugar for:

for node in tree:
if not node.haschildre n():
continue
<do something with node>


Mhhh, your unsugared form remind me of darks hours with primitive BASICS in my
youth - the kind Dijsktra commented on. Why don't you write

for node in tree:
if node.haschildre n():
<do something with node>

?
May 22 '06 #5
Am Montag 22 Mai 2006 11:27 schrieb Boris Borcic:
Mhhh, your unsugared form remind me of darks hours with primitive BASICS in
my youth - the kind Dijsktra commented on. Why don't you write

for node in tree:
if node.haschildre n():
<do something with node>


As I've replied on python-dev, indentation is not always a good thing,
especially if the for-body is longer than a few lines.

The "if not: continue" form allows you to keep the indentation at one level,
so that it's pretty clear what is part of the loop body, and what is not. If
you add an extra indentation, your mind has to keep track of the indentation,
and will expect an "else:" somewhere, which in the use case I propose won't
happen. At least that's what my mind does, and is majorly confused, if the
else doesn't appear.

This certainly is personal taste, and AFAICT there are pretty few people who
feel like I do. But, basically, I find it easier to have one level of
indentation, and to test for the negated condition, than to put the loop body
in an enclosing if-statement, which will always add an extra level of
indentation. I put forth the proposal, because it allows you to save this
level of indentation, which makes the code more readable for me.

Anyway, the PEP has already been rejected on python-dev, and I'm currently
just rewriting it with the positive and negative things that have so far been
said, so basically, it'll just be there so that people can be pointed at it
when anybody else'll ask for it.

--- Heiko.
May 22 '06 #6
+1 It does seem like a natural unificiation of the language -- one less
exception to learn.

-- Russell
May 22 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

31
3898
by: John Roth | last post by:
I'm adding a thread for comments on Gerrit Holl's pre-pep, which can be found here: http://tinyurl.com/2578q Frankly, I like the idea. It's about time that all of the file and directory stuff in the os module got objectified properly (or at least with some semblance of OO propriety!) In the issues section:
3
1499
by: Christoph Becker-Freyseng | last post by:
Hello, recently there was a lot discussion about a new Path-class. So Gerrit Holl started to write a pre-PEP http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html We tried to summarize the good ideas and suggestions. Some are still missing and concepts of already existing modules have to be added/thought over. Furthermore it turns out that not a new class is needed but a module. The pre-PEP is already quite big --- Gerrit Holl
6
1855
by: Skip Montanaro | last post by:
I wrote PEP 304, "Controlling Generation of Bytecode Files": http://www.python.org/peps/pep-0304.html quite awhile ago. The first version appeared in January 2003 in response to questions from people about controlling/suppressing bytecode generation in certain situations. It sat idle for a long while, though from time-to-time people would ask about the functionality and I'd respond or update the PEP. In response to another recent...
8
1725
by: Micah Elliott | last post by:
I also have this living as a wiki <http://tracos.org/codetag/wiki/Pep> if people would like to add comments there. I might try to capture there feedback from this group anyway. First try at a PEP -- thanks for any feedback! Please add **NOTE:** comments to the bottom of this wiki document using `WikiRestructuredText`:trac:. =======================================
77
3907
by: Ben Finney | last post by:
Howdy all, PEP 354: Enumerations in Python has been accepted as a draft PEP. The current version can be viewed online: <URL:http://www.python.org/peps/pep-0354.html> Here is the reStructuredText source as it is today. Please discuss it here so I can see what issues people may have.
0
8175
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8482
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7168
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6111
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4082
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2610
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1487
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.