Skip to content

Instantly share code, notes, and snippets.

@vovanmix
Last active July 5, 2016 19:56
Show Gist options
  • Select an option

  • Save vovanmix/762de3076df3b9a9e5dc08a9f04adf35 to your computer and use it in GitHub Desktop.

Select an option

Save vovanmix/762de3076df3b9a9e5dc08a9f04adf35 to your computer and use it in GitHub Desktop.
python snippets

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment