Notes for Effective Python

Aug 15, 2020 00:00 · 202 words · 1 minute read Python

Reading notes for the book Effective Python: 90 Specific Ways to Write Better Python.

1. Pythonic thinking

Follow PEP style guide:

  • Functions, variables, and attributes should be in lowercase_underscore format.
  • Protected instance attributes should be in _leading_underscore format.
  • Private instance attributes should be in __double_leading_underscore format.
  • Classes (including exceptions) should be in CapitalizedWord format.
  • Module-level constants should be in ALL_CAPS format.
  • Instance methods in classes should use self, which refers to the object, as the name of the first parameter.
  • Class methods should use cls, which refers to the class, as the name of the first parameter.

Expressions and Statement:

  • Use inline negation: if a is not b
  • Check for empty containers: if not somelist, don’t use if len(somelist)==0

Format:

  • "{}={}".format(key, value)
  • "{}={:.2f}".format(key, value)
  • "{1}={0}".format(key, value)

Enumerate:

  • enumerate(x, 1) starts counting from 1 instead of 0.
  • for index, value in enumerate(x).
  • The zip built-in function can be used to iterate over multiple iterators in parallel.
  • zip truncates its output silently to the shortest iterator if you supply it with iterators of different lengths.
  • Use the zip_longest function from the itertools built-in module if you want to use zip on iterators of unequal lengths without truncation.

2. Lists and Dictionaries

(To be continued)

tweet Share

Related Articles