Idiomatic Python: Improve Clarity

##Clarify function calls with keyword arguments

1
2
3
4
5
#NOT SO GOOD
twitter_search('@obama', False, 20, True)
#GOOD
twitter_search('@obama', retweets=False, numtweets=20,popular=True)

##Clarify multiple return values with named tuples
namedtuple is a factory function for creating tuple subclasses with named fields.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#NOT SO GOOD
def test():
#some test here
attempted = 4
failed = 0
return failed, attempted# -> (0, 4)
#GOOD
from collections import namedtuple
TestResult = namedtuple('TestResult', ['failed', 'attempt'])
def test():
#some test here
attempted = 4
failed = 0
return TestResult(failed, attempted)# -> TestResults(failed=0, attempted=4)

##Unpacking sequences

1
2
3
4
5
6
7
8
9
10
p = 'Raymond', 'Hettinger', 0x30, 'python@example.com'
# NOT SO GOOD
fname = p[0]
lname = p[1]
age = p[2]
email = p[3]
#GOOD
fname, lname, age, email = p