block by joyrexus 11187638

Basic python idioms

A few python idioms

Test for “truthy” and “falsy” values

boys = ['bob', 'joe']
girls = ['ann', 'jill']
parents = []
police = False
drinks = { 'gin': ['tanquerey', 'brokers', 'smalls'] }
party = False

if boys and girls and not parents and not police:
    party = True

assert party

Use in where possible

assert 'x' in 'fox'
assert 'x' in ['f', 'o', 'x']
assert 'x' in set(['f', 'o', 'x'])
assert 'x' in {'f': 'F', 'o': 'O', 'x': 'X'}

Take advantage of value swapping

x, y = 1, 0
assert x is 1
assert y is 0

x, y = y, x
assert x is 0
assert y is 1

Use ''.join() to build strings

seq = ['f', 'o', 'o']
assert ''.join(seq) == 'foo'
assert 'a\tb' == '\t'.join(['a', 'b'])

Ask forgiveness rather than permission

freq = {}
try:
    value = freq['q']
except KeyError:
    value = None
assert not value

Build lists using comprehensions

result = [(i, i ** 2) for i in range(100) if i < 10 and i % 2]
expected = [(1, 1), (3, 9), (5, 25), (7, 49), (9, 81)]
assert result == expected

Use zip to create dicts from lists of keys and values

keys = ['a', 'b', 'c']
vals = [100, 200, 300]
assert dict(zip(keys, vals)) == {'a': 100, 'b': 200, 'c': 300}

Take advantage of hash-map defaults

freq = {'a': 1, 'b': 2, 'c': 3}
assert freq.get('d', 0) is 0
freq.setdefault('d', 0)
assert freq['d'] is 0

from collections import defaultdict as dd

freq = dd(int, [('a', 1), ('b', 2), ('c', 3)])
assert freq['c'] is 3
assert freq['d'] is 0
freq['d'] = 4
assert freq['d'] is 4

Make your scripts importable and executable

Use if __name__ == '__main__' for this.

For example, suppose we have the following in greet.py:

def hi():
    return 'Hello from module {0}!'.format(__name__)

if __name__ == '__main__':
    print(hi())

Running from the command line:

$ python greet.py
Hello from module __main__!

Importing as a module:

>>> import greet
>>> greet.hi()
Hello from module greet!

See also