I am reading the book Effective Python: 90 Specific Ways to Write Better Python (click here to see it) and will write 18 blog entries, 1 per week, each covering 5 ways. To keep everything bite-sized (no pun intended), I will write a synopsis for each way; many things will be left out, but I will try to capture the most important ones.
I will use Python 3 for the examples.
Item #01: Know which version of Python you are using.
This is achieved with the command $ python --version or at run-time:
import sys
print(sys.version)
Item #02: Follow the most recent PEP style guide.
It is extensive. Click here to learn more. Memorize it! A few highlights are: spaces over tabs, 4 spaces of indentation, def this_is_my_function(self):, class ThisIsMyClass:, THIS_IS_MY_GLOBAL_VARIABLE = foo, etc.
Item #03: Know the differences between bytes and str.
Python has two types that represent sequences of character data: bytes and str.
Instances of bytes contain raw, unsigned, 8-bit values that are often displayed in the ASCII encoding:
x = b'h\x65llo'
print(list(x), x, type(x))
>>>
[104, 101, 108, 108, 111] b'hello' <class, 'bytes'>
Instances of str contain Unicode code points that represent textual characters from human languages.
Item #04: Prefer interpolated f-strings over C-style format strings and str.format.
Let name = 'John Doe'. Prefer to do this: f'My name is {name}.' over 'My name is %s.' % name and 'My name is {0}.'.format(name).
This is a general rule. The documentation says that the logging library is optimized to use C-style strings; this could make a difference at large scales.
Item #05: Write helper functions instead of complex expressions.
Suppose that you have a Chess class that has a complicated function def play_best_move(self):. It is better to rewrite it as follows (to give a simple example):
def play_best_move(self):
legal_moves = self.get_legal_moves()
best_move = self.rank_moves_inc(legal_moves)[-1]
self.play_move(best_move)
Note that these are reusable functions. For example:
def play_worst_move(self):
legal_moves = self.get_legal_moves()
worst_move = self.rank_moves_inc(legal_moves)[0]
self.play_move(worst_move)