Last active
September 29, 2015 04:21
-
-
Save moosh3/c2eb8abd5945fc1dc842 to your computer and use it in GitHub Desktop.
Pythonic idioms, and conventions for reference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python Code Style | |
# Code like a Pythonista; Idioms | |
# http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html | |
my_dict = { | |
"Name": "Alec", | |
"Age": 19, | |
"killa": True | |
} | |
for key in my_dict: | |
print key, my_dict[key] | |
# Output: | |
# > Age 19 | |
# > killa True | |
# > Name Alec | |
# > None | |
evens_to_50 = [i for i in range(51) if i % 2 == 0] | |
print evens_to_50 | |
evens_to_50 = [] | |
for i in range(51): | |
if i % 2 == 0: | |
evens_to_50[i] | |
''' | |
When there are multiple main exit points for its normal course, | |
it becomes difficult to debug the returned result, so it | |
may be preferable to keep a single exit point. | |
''' | |
def complex_function(a, b, c): | |
if not a: | |
return None # Raising an exception might be better | |
if not b: | |
return None # Raising an exception might be better | |
# Some complex code trying to compute x from a, b and c | |
# Resist temptation to return x if succeeded | |
if not x: | |
# Some Plan-B computation of x | |
return x # One single exit point for the returned value x will help | |
# when maintaining the code. | |
''' | |
Because lists are mutable, using there * operator | |
when creating length-N list of the same thing will create | |
a list of N references to the same list, which is probably | |
not what you want. | |
''' | |
# Four lists of the same thing | |
four_nones = [None] * 4 | |
# Good | |
four_lists = [[] for __ in xrange(4)] | |
''' | |
The following are some conventions for making your | |
code easier to read | |
''' | |
# Easy way to create list of words | |
items = 'zero one two three'.split() | |
# A commond idion for creatings strings | |
letters = ['j', 'o', 'i', 'n'] | |
word = ''.join(letters) | |
# Bad | |
if attr == True: | |
print 'True!' | |
if attr == None: | |
print 'attr is None!' | |
# Good | |
if attr: # Just check the value | |
print 'attr is truthy!' | |
# or check for the opposite | |
if not attr: | |
print 'attr is falsey!' | |
# or, since None is considered false, explicitly check for it | |
if attr is None: | |
print 'attr is None!' | |
## Filter elements greater than 4 | |
# Bad | |
a = [3, 4, 5] | |
b = [] | |
for i in a: | |
if i > 4: | |
b.append(i) | |
# Good | |
a = [3, 4, 5] | |
b = [i for i in a if i > 4] | |
# Or: | |
b = filter(lambda x: x > 4, a) | |
## Add three to all list members. | |
# Bad | |
a = [3, 4, 5] | |
for i in range(len(a)): | |
a[i] += 3 | |
# Good | |
a = [3, 4, 5] | |
a = [i + 3 for i in a] | |
# Or: | |
a = map(lambda i: i + 3, a) | |
## List Comprehensions | |
## Traditional, bad | |
new_list = [] | |
for item in a_list: | |
if condition(item): | |
new_list.append(fn(item)) | |
# Good | |
new_list = [fn(item) for item in a_list | |
if condition(item)] | |
# Bad | |
total = 0 | |
for num in range(1, 101): | |
total += num * num | |
# Good, list comprehension | |
total = sum([num * num for num in range(1, 101)]) | |
## Using the enum() function instead of range(len()) | |
## to iterate over items | |
# Bad | |
for i in range(len(items)): | |
print i, items[i] | |
# Good | |
for (index, item) in enumerate(items): | |
print index, item | |
# To print, we must use a list() wrapper, for enumerate is a generator | |
>>> print list(enumerate(items)) | |
[(0, 'zero'), (1, 'one'), (2, 'two'), (3, 'three')] | |
## Use enumerate() to keep a count of | |
## your place in the list | |
a = [3, 4, 5] | |
for i, item in enumerate(a): | |
print i, item | |
# Output | |
# 0 3 | |
# 1 4 | |
# 2 5 | |
## Appending items | |
def bad_append(new_item, a_list=[]): | |
''' | |
The problem here is that the default value of a_list, an empty list, is evaluated at function definition time. | |
So every time you call the function, you get the same default value | |
''' | |
a_list.append(new_item) | |
return a_list | |
# Good | |
def good_append(new_item, a_list=None): | |
if a_list is None: | |
a_list = [] | |
a_list.append(new_item) | |
return a_list | |
## Building a dictionary from two lists | |
given = ['John', 'Eric', 'Terry', 'Michael'] | |
family = ['Cleese', 'Idle', 'Gilliam', 'Palin'] | |
names = dict(zip(given, family) | |
# Read from a file | |
with open('file.txt') as f: | |
for line in f: | |
print line |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment