11 March 2016

the zen of python

        there should be one
        and preferably only one
        obvious way to do it

basics

  1. whitespace formatting

    1. whitespace is ignored inside parentheses and brackets

       long_winded_computation = (1 + 2 + 3 + ... + 12 + 
                                  13 + 14 + 15 + ... + 20)
      
    2. making code easier to read

       list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
      
       easier_to_read = [ [1, 2, 3],
                          [4, 5, 6],
                          [7, 8, 9] ]
      
    3. backslash to indicate continues on next line

       two_plus_three = 2 + \
                        3
      
    4. hard to copy and paste

       for i in range(1, 6):
      
           # notice the blank line
           print i
      
      
       # paste into python shell
       IndentationError: expected an indented block
      
       # in ipython shell
       # use magic %paste
      
  2. modules

    1. import

       import re
       my_regex = re.compile('[0-9]+', re.I)
      
    2. alias

       import re as regex
       my_regex = regex.compile('[0-9]+', re.I)
      
    3. standard convention

       import matplotlib.pyplot as plt
      

    1.without qualification

         from collections imiport defaultdict, Counter
         lookup = defaultdict(int)
         my_counter = Counter()
    
  3. arithmetic

         # a = 2
         a = 5 / 2
    
         from __future__ import division
         # a = 2.5
         a = 5 / 2
    
         # a = 2
         a = 5 // 2
    
  4. functions

    1. use def

       def double(x):
           """docstring"""
           return x * 2
      
    2. functions are first-class

       def apply_to_one(f):
           """calls the function f with 1 as its argument"""
           return f(1)
      
       my_double = double
       x = apply_to_one(my_double)
      
    3. assign lambda to variables

       # don't do this
       another_double = lambda x: x * 2
      
       # do this instead
       def another_double(x) return x * 2
      
    4. default arguments

       def my_print(message="my default message"):
           print message
      
       my_print('hello')
       my_print()
      
       def substract(a=0, b=0):
           return a - b
      
       substract(10, 5)
       substract(0, 5)
       substract(b=5)
      
  5. strings

    1. single or double quotation

    2. encode special character

       tab_string = '\t'
       len(tab_string)
      


blog comments powered by Disqus