# Defending the ternary operator

Paul Paterson hamonlypaulpaterson at houston.rr.com
Sun Feb 9 02:14:05 CET 2003

"Andrew Dalke" <adalke at mindspring.com> wrote in message
news:b2462f\$qbs\$1 at slb0.atl.mindspring.net...
> Andrew Koenig:
> > As an experiment, ... <snip experiment to look at examples of
conditional operator>

Continuing the experiment to look at Python code which might use the
conditional operator....

If my regular expression is correct (and it probably isn't because I'm not
good at them), then a quick scan of my Python22 directory structure finds
769 matches of the following pattern,

if <something>
variable = <some value>
else:
variable = <some other value>

in 381209 lines of code. I leave the statistical interpretation to the

I intend to post each one with an analysis of why they would or wouldn't be
better done using the new form....

In the meantime, here's the code - you can make up your own mind.

import re, sys, os

pattern =
re.compile(r"(^\s*if.*?\$\s+(?P<var>\S+?)\s*=.*?\$\s*else:\s+(?P=var).*?\$)",
re.MULTILINE)

total_lines = 0
total_matches = 0

def look(arg, d, names):
"""Look in directory d for examples of conditional expressions"""
for filename in names:
if os.path.splitext(filename)[1] in (".py", ".pyw"):
try:
matches = pattern.findall(text)
except:
print "%s::%s - failed!" % (d, filename)
else:
global total_matches, total_lines
total_matches += len(matches)
total_lines += len(text.splitlines())
print "%s::%s - %d (%d/%d)" % (d, filename, len(matches),
total_matches, total_lines)
for match in matches:
print "\n\n%s\n\n" % match[0]

path = os.path.join(sys.exec_prefix, "lib")
os.path.walk(path, look, None)