Idiomatic Python: Strings, Conditions and Tests

##Concatenating strings

1
2
3
4
5
6
7
8
9
10
11
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
#NOT SO GOOD
s = names[0]
for name in names[1:]:
s += ', ' + name
print s
#GOOD
print ', '.join(names)

##EAFP is preferable to LBYL
“It’s Easier to Ask for Forgiveness than Permission.”

Look Before You Leap.”

1
2
3
4
5
6
7
8
9
10
11
12
13
d = {'x': '5'}
#NOT SO GOOD
if 'x' in d and isinstance(d['x'], str) and d['x'].isdigit():
value = int(d['x'])
else:
value = None
# GOOD
try:
value = int(d['x'])
except (KeyError, TypeError, ValueError):
value = None

Throwing exceptions is not “expensive” in Python unlike e.g. Java.
Rely on duck typing rather than checking for a specific type.

##Use truthy and falsy values

1
2
3
4
5
6
7
8
9
10
11
name = 'Safe'
pets = ['Dog', 'Cat', 'Hamster']
owners = {'Safe': 'Cat', 'George': 'Dog'}
# NOT SO GOOD
if name != '' and len(pets) > 0 and owners != {}:
print('We have pets!')
# GOOD
if name and pets and owners:
print('We have pets!')

##Use pdb

1
2
import pdb
pdb.set_trace()