python code mistakes

  1. try, except not specific

    try:

      ....

    except:

      ....
    

this not good, ctrl+c can not stop the script, keyboard interrupt exception also handled by except.

  try:
     ....
  except Exception :
     ....
  1. Get real useful exception info

      try:
       ......
     except Exception as e:
         print(e)
         or log(e)
    

    this way will get a lot of not useful or confused info

    do this:

          import traceback
    
          try:
            .........
    
          except Exception as e:
    
           traceback.print_exc()
    
          or 
               print(traceback.format_exc())
               log(tracback.format.exc())
    
    
  2. Check membership

    using set instead of list

    name_lst=[.....]
    name_set={..........}
    
    if name in name_lst:
       do something
    

    this take longer time, better to do this

    if name in name_set:

          do something
    
  3. use list as default parameter in fun

     def agg_name_with_lst( names, agg_lst=[]):
         ........
    
     agg_lst only create one time for many function calls
    

    do this :

      def agg_name_with_lst( names, agg_lst=None):
         if isinstance(agg_lst, type(None))
               agg_lst=list()
          else:
               do  agg