Python Tricks Review

Python Tricks by Dan Bader is book about best practices and getting a deeper understanding of Python. The format is that of small digestable bits. Well explained but provocative and actionable most of the times.


The Book

The book started out on Twitter as a series of Python code screenshots. Dan Bader - main mind beyond realpython.com - was impressed by the reaction and started to work more on the format. Tweets eveloved into mails discussing the tricks and offering more context. Repeat and iterate and you get the book.

The first thing to get clear is to define what’s a Python Trick. Dan has its own definition but for out purposes a python trick is a learning opportunity. Each trick offers a view on real applied Python but it does not stop there. We find general discussions and “receipes”, but not in a cookbook style. If we copy and paste Dan’s code, we are not going to achieve much in terms of practical wonderful results.

The code offered is a working explaination of a concept and an occasion to learn more. Each code snippet explores a topic about coding and programming.


Contents

Here’s list of the tricks, as I took note of them while scrolling the book and seeing what I’ve highlighted:

  1. debug with assert: they’ll signal unrecoverable errors;
  2. don’t use assert for data validation;
  3. remember assert can be turned off, so all your checks are useless;
  4. beware of avoiding non empty tuples () to assert. Non-empty tuplets are truthy, so the assertion will never fail;
  5. write lists in a git friendly way: spread out the elements, adding a comma (,) after all the element - yes, last one included;
  6. use with statements to open files and handle resource consuming tasks;
  7. create context managers or incorporate ’__enter__’ and ’__exit__’ methods to your classes to include “with” statements into your objects. (Yes, that’s quite an horrible explanation. Before getting the book you can have a look at the contextlib module documentation which allows you to decorate try/yield/finally statements and turn them into context manager);
  8. inspect objects with dir() to know their attributes;
  9. tricks about the 4 ways to format strings;
  10. importing the dis module (here’s the module documentation) to perform debugging and evaluate performance time;
  11. review of functions as first class objects (including closures and lambdas);
  12. decorators;
  13. using functools.wraps to recover metadata from your decorators;
  14. * operations: args and kwargs and function arguments unpacking;
  15. == for equality and ‘is’ for being identical;
  16. adding __repr__ to classes;
  17. define your own exception classes;
  18. abc usage (abstract base class, this module);
  19. tricks with namedtuplets;
  20. static methods vs. class methods (not forgetting class instances)
  21. data structure tricks: ordereddict, defaultdict, chainmap and other fancy things useful for interviews;
  22. python lists are dynamic arrays!
  23. sets and multisets;
  24. frozenset - immutable set;
  25. collections.Counter - a multiset;
  26. stacks (LIFO) vs. queue (FIFO) (with deque, LifoQueue)
  27. looping and iterating;
  28. using the enumerate() function to write Pythonic loops;
  29. comprehensions;
  30. sushi operator (:);
  31. filtering generators;
  32. iterator chains;
  33. use the get() method in dictionaries;
  34. peeking behind bytecode curtain;
  35. and much more.

As you can see, there’s quite a lot going on.


Style and Exercises (if Any)

Each section has a summary in the form of key points. There are no “proper” exercises but actually each Python trick is an exercise on its own as you follow it along on the interpreter. You can also see the whole book as a big exercise in the form “try to incorporate some of these in your code”.


Favourite Pick(s)

What I liked most about the book is that it allows you to see different problems from those of a standard reference book, a specific cookbook and dedicated tutorials. One of the first thing is sharing code with others and working in a team environment.

Another thing I appreciated are the “Comparing Feature X Implementation in Python” (e.g. how to implement stacks) and the “are we sure we’re getting the differences between X and something similar to X?” (e.g. generators vs. list comprehension). Dan often tries to strike a balance and offer some general rule.

As I said, the book is written having different programmers in mind. And, well, there’s not only Python out there. So, yep, in the book there are comparisons with different languages, like for example when discussing a Java code smell for while and for loops (For loops are really for-each loops). Depending on what you are familiar with, you’ll get an opportunity to add something more. (Something that impressed me was the part about simulating switch code with dictionaries).

What’s more? Oh, a nice Koan at the end about truthyness and a furhter tips on Python productivity.

Ok, given what I’ve said up until now the book looks good but it sounds messy and disorganized. I guess that’s probably my bad. The best part of the book is that it builds on.

That’s something Dan doesn’t say explicitely. Tricks are organized by area or theme (just look at the table of contents of the book). But the genious part is that, if in section N.1 we are talking about X and something Y is briefly mentioned, rest assured you’ll find your Y in the next N.2 or N+1. Brilliant! (Oh, and cross-references work pretty well throught the book.)


Best Practice After Finishing the Book (Extending the Stuff (Prolonging the Magic))

The book is a call for action in two ways:

  1. Dan tells you the first: don’t let this book be just another programming book you’ve finished, used it out there in the wild, in your day to day interaction with software.
  2. The second is probably the most important and comes naturally after finishing the book. Keep track of you own Python tricks. Open a Markdown document or a Jupyter Notebook to track your Python tricks. Don’t forget how this book stated.