A few python idioms
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
in
where possibleassert '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'}
x, y = 1, 0
assert x is 1
assert y is 0
x, y = y, x
assert x is 0
assert y is 1
''.join()
to build stringsseq = ['f', 'o', 'o']
assert ''.join(seq) == 'foo'
assert 'a\tb' == '\t'.join(['a', 'b'])
freq = {}
try:
value = freq['q']
except KeyError:
value = None
assert not value
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
zip
to create dicts from lists of keys and valueskeys = ['a', 'b', 'c']
vals = [100, 200, 300]
assert dict(zip(keys, vals)) == {'a': 100, 'b': 200, 'c': 300}
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
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!