Idiomatic Python Examples
Ternary Operator replacement
Don't Write This:
a = True
value = 0
if a:
value = 1
print(value)
a = True
value = 1 if a else 0
print(value)
Write This:
Use the ‘in’ keyword
Don't Write This:
Write This:
city = 'Nairobi'
found = city in {'Nairobi', 'Kampala', 'Lagos'}
city = 'Nairobi'
found = False
if city == 'Nairobi' or city == 'Kampala' or city == 'Lagos':
found = True
Don't Write This:
cities = ['Nairobi', ‘Kampala’, ‘Lagos’]
index = 0
while index < len(cities):
print(cities[index])
index += 1
cities = [‘Nairobi’, ‘Kampala’, ‘Lagos’]
for city in cities:
print(city)
Write This:
Use ‘return’ to evaluate expressions, in addition to return values
Don't Write This:
def check_equal(x, y):
result = False
if x == Y:
result = True
return result
def check_equal(x, y):
return x == y
Write This:
Formatting Strings
Don't Write This:
def user_info(user):
return 'Name: ' + user.name + ' Age: '+ user.age
def user_info(user):
return 'Name: {user.name} Age: {user.age}'.format(user=user)
Write This:
List comprehension
Don't Write This:
Write This:
ls = [element for element in range(10) if not(element % 2)]
ls = list()
for element in range(10):
if not(element % 2):
ls.append(element)
Enumerate(list)
Don't Write This:
ls = list(range(10))
index = 0
while index < len(ls):
print(ls[index], index)
index += 1
ls = list(range(10))
for index, value in enumerate(ls):
print(value, index)
Write This:
Dictionary Comprehension
Don't Write This:
emails = {}
for user in users:
if user.email:
emails[user.name] = user.email
emails = {user.name: user.email for user in users if user.email}
Write This:
Use the default parameter of ‘dict.get’ to provide default values
Don't Write This:
auth = payload.get('auth_token', 'Unauthorized')
Write This:
auth = None
if 'auth_token' in payload:
auth = payload['auth_token']
else:
auth = 'Unauthorized'
Don’t Repeat Yourself (DRY)
Don't Write This:
if user:
print('------------------------------')
print(user)
print('------------------------------')
print('{0}\n{1}\n{0}'.format('-'*30, user))
Write This:
Don't Write This:
Write This:
my_container = ['Larry', 'Moe', 'Curly']
index = 0
for element in my_container:
print ('{} {}'.format(index, element))
index += 1
my_container = ['Larry', 'Moe', 'Curly']
for index, element in enumerate(my_container):
print ('{} {}'.format(index, element))
Idomatic Python
By Abhyuday Pratap Singh
Idomatic Python
- 710