[Python-Dev] Conditional For Statements

Nick Coghlan ncoghlan at gmail.com
Mon May 19 16:16:51 CEST 2008


Ryan Hitchman wrote:
> This would make the syntax closer to that of generators, which have
> 'for variable in iterable if condition', 

Incorporating the filter condition into the list comprehension syntax 
(and later into generator expressions) is necessary because they need to 
be written as a single expression. The same doesn't hold true for loop 
filters: it is quite possible to keep the looping and filtering concerns 
separated into different statements, and there's no compelling reason 
for merging them.

> would improve code clarity by increased brevity

Increased brevity != improved code clarity (in fact, being too terse can 
obfuscate things - just look at Perl)

 > not negating boolean expressions.

Except, of course, for those cases where it is easier to define the 
condition for items to skip than it is to define the condition for items 
to include.

> Following are examples of current code with what the new code would
> be, taken from the Python 3.0a5 tarball.

Using just the standard idiom of a separate if statement to do the 
filtering:

for (x, y), cell in self.cells.items():
     if x <= 0 or y <= 0:
         continue
     # ...

for modname in modnames:
     if not modname or '.' in modname:
         continue
     # ...

for w in wafter:
     if dict.get(w):
         continue
     # ...

for K,V in items:
     if V == "": continue
     if K not in attrs: continue
     # ...

for opensslFuncName in dir(_hashlib):
     if opensslFuncName.startswith('openssl_'):
         continue
     # ...

I'm not really seeing how the readability of any of those examples is 
enhanced by being able to merge the filter condition into the first line 
of the for loop. The one example which was already written that way 
through the use of filter() is actually easy to read with the addition 
of the vertical whitespace needed for the idiomatic form.

The separate statement approach also scales far more cleanly to more 
complex filter conditions. For example, some code of mine includes a 
loop that looks like:

for name in dirnames:
     if not os.path.exists(name):
         continue
     if not os.path.isdir(name):
         continue
     # Process named directory

This conveys the order of checks far more clearly than would be the case 
if the os.path calls were hidden on the end of the loop invocation.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list