Style Guide for Python Code - https://www.python.org/dev/peps/pep-0008/
Python style guide checkers - pep8, flake8
Access an item in a dict that is not available. The dict returns a new object using the function you passed as argument to the constructor
#long:
somedict = {}
if somekey not in somedict:
somedict[somekey] = []
somedict[somekey].append(somevalue)
#shorter:
import collections
somedict = collections.defaultdict(list)
somedict[somekey].append(somevalue)
#long:
if somekey not in somedict:
somedict[somekey] = somedefault
value = somedict[somekey]
#shorter:
value = somedict.setdefault(somekey, somedefault)Execute block if there were no break
for x in [1, 2, 3, 4, None, 5, 6]:
if not x:
break
else:
print("Everything is True")Check array elements for True
#also has any()
if all([1, 2, 3, 4, None, 5, 6]):
print("Everything is True")Read file
def fetch(path, fromTime, untilTime=None, now=None):
with open(path, 'rb') as fh:
return file_fetch(fh, fromTime, untilTime, now)