10 recommended Python code habits


In daily work, we need to write many scripts and small projects, share some experience and code habits, be subjective, take care of ourselves, and seek common ground while reserving differences.

  1. Use tqdm package to check the processing progress. Complex situations can be consideredfastprogress

  2. There are too many parameters and you want the terminal to modify them directly. RecommendedYACS — Yet Another Configuration System

  3. If there are many configurable parameters, which are easy to make mistakes, the confirmation process can be added

    enter = raw_input("confirm (y/n): ")
    if enter.lower() != 'y':
  4. Without front-end knowledge, you can use the open source library streamlit to quickly build web debugging tools related to machine learningStreamlit — The fastest way to build custom ML tools

    import streamlit as st
    st.write('Hello, world!')
  5. If possible, try to format and typeset

  6. The processing of files by small scripts can be directly output through print, which is convenient for further processing with pipeline commands

  7. When running an error report, add an exception capture + IPDB debugging directly to that code, which is simple and efficient

    except xxxError:
         import ipdb; ipdb.set_trace()
  8. Don’t build wheels repeatedly, but also pay attention to collecting and sorting out your commonly used code fragments

    def split_chunks(data, n):
         if data is None:
             return None
         N = len(data)
         m = int(math.ceil(N / float(n)))
         res = [[] for i in range(n)]
         for i in range(n):
             res[i] = data[i*m: (i+1)*m]
         return res
  9. Use more list expressions to simplify common codes.

    with open(path) as f:
         lines = [l.strip() for l in f.readlines()]
  10. Single file scripts can be long, but single functions are not allowed to be smelly and long. Clarify the logic and divide them into multiple functions for easy modification.

This work adoptsCC agreement, reprint must indicate the author and the link to this article