Book Review: Python Tricks

If you've been around Python for a while, then you're probably familiar with Dan Bader. He likes to help people up their Python game and share his knoweledge of the language. Because of that, he released his own book, Python Tricks.

 
 

The book has seven sections of Python goodness:

  • Clean Python Patterns
  • Effective Functions
  • Classes
  • Data Structures
  • Loops
  • Dictionaries
  • Productivity

Let's look at an example in each of the above items so you can have an idea of what is in the book. These examples are ones that I have learned from when reading the book. Code examples in this post are my own.

Clean Python - Assertions

The very first tip in this book goes over using assertions in Python. Assertions, if you aren't familiar, is a way to well, assert if a condition is true. More specifically, a condition in which you expect to be true. If you have an assertion and it turns out to false, it will throw an AssertionError.

2019-03-30 16_55_19-Clipboard.png

If an assertion is caught it's a good idea to see why. Doing so will allow you to catch bugs that you may not have been able to catch before which is why having assertions are helpful.

Effective Functions - *args and **kwargs

When starting out in Python you may come across a method like the below:

def main(*args, **kwargs):
    print(args)
    print(kwargs)

Seeing something like this for the first time and, like me, you'll wonder what in the world that means.

*args are extra positional arguments you can pass in. The * in front tells it to gather all of those into a tuple. So if we take the method definition from above we can print the *args.

main("hello", "world")
2019-03-30 17_36_06-Clipboard.png

The **kwargs parameter does the same thing, but instead of a tuple it will be a dictionary since the kw in front of the args stands for "key word".

2019-03-30 17_36_50-Clipboard.png

Classes - Named Tuples

Tuples in Python are essentially a collection that is immutable. That is, once it's definied it can't be changed. To easily spot a tuple, the values in it will be enclosed by parentheses.

t = (1, 2, 3, 4, "five")
t
2019-03-30 17_48_47-Clipboard.png

However, if we want to get access to get access to the first item of the tuple, there's no dot notation to give us access to it.

2019-03-30 17_50_58-Clipboard.png

Though, we can use slicing to access it.

t[0]
2019-03-30 17_57_26-Clipboard.png

With a NamedTuple we can create a tuple and access items in it with the dot notation.

from collections import namedtuple

t = namedtuple("t", ["one", "two", "three", "four", "five"])

items = t(1, 2, 3, 4, "five")
2019-03-30 17_59_51-Clipboard.png

Data Structures - Sets

Sets are a data structure that simply gives unique values. This can be quite useful if you want to remove duplicates from a list.

set([1, 2, 3, 4, 2, 5, 3])
2019-03-30 18_07_38-Clipboard.png

Loops - Comprehensions

List comprehensions are perhaps one of my favorite things in Python. It is essentially sytactic sugar on top of using a for loop and, once understood, can be easier to read since it is only in one line. For example, let's say we have the below loop:

item = []
for i in range(0, 10):
    item.append(i + 1)

print(item)
2019-03-30 18_43_38-Clipboard.png

We can rewrite it using a list comprehension:

[i + 1 for i in range(0, 10)]
2019-03-30 18_44_09-Clipboard.png

What if we need an if statement in the loop, like below?

item = []
for i in range(0, 10):
    if i % 2 == 0:
        item.append(i + 1)

print(item)
2019-03-30 18_44_39-Clipboard.png

That can also be broken down into a list comprehension.

[i + 1 for i in range(0, 10) if i % 2 == 0]
2019-03-30 18_45_05-Clipboard.png

Dictionaries - Default Values

Often, when checking if a value is in a dictionary, it's not always known if that value is in the dictionary in the first place. The get method on dictionaries is a good way to get the value if it is in the dictionary or to return a default value if it is not in the dictionary.

For example, let's say we have the below dictionary.

d = {"x": 1, "y": 2}

We can get the y value with the get method.

d.get("y")
2019-03-30 18_56_17-Clipboard.png

But if we try to get the value from z which doesn't exist in the dictionary, we can give a second parameter to the get method to return that value as default if the key doesn't exist.

d.get("z", 0)
2019-03-30 18_56_53-Clipboard.png

Also, if we don't specify the default value and the key doesn't exist in the dictionary, the get method won't return anything.

d.get("z")
2019-03-30 18_57_36-Clipboard.png

Productivity - dir

While Python is a great language it is also a bit weird to work with when trying to explore through code what methods or properties a variable can have. That's one of the nice things with C# and it being a typed language. I can use the dot notation and intellisense to see what is available on a variable. With Python, though, that may not always work even in great editors such as PyCharm and Jupyter.

This is where the dir method comes to the rescue. Using this method we can see exactly what method and properties are on a variable.

For example, let's say you wanted to see what all is avilable on a list object.

x = [1, 2]
dir(x)
2019-03-30 19_06_30-Clipboard.png

The dir method has saved me a lot of time trying to find what's available on objects instead of having to hunt down the documentation.


I consider myself a beginner to intermediate in Python. Some of the tricks in here I've seen before, such as asserts and list comprehensions, but most of the ones in this book I haven't. I definitely learned quite a bit more about using Python. Both for cleaner code and to utilize what the language has to offer whether than defaulting to what I already know from another language.

Whether you're just beginning or a pro in Python, there's something in this book to learn from. Maybe there'll be a second edition soon.

Top 10 Sessions at PyCon 2018

PyCon has a very nice history of releasing videos of all of their sessions in a very timely manner. Although, it's up to me to actually have time to watch them.

Now that I've gone through several videos I wanted to share the top ten of them that I think will give the most to people who are interested in which sessions they should watch.

Python 2 to 3: How to Upgrade and What Features to Start Using by Trey Hunner

With the announcement of Python 2 coming to a complete end in the very beginning of 2020, it's a good idea to start thinking of how to upgrade your existing Python 2 code to Python 3. Trey gives a great talk on ways you can start upgrading and the best features of Python 3 you can start using.

You're an expert. Here's how to teach like one by Shannon Turner

Shannon goes through some nice tips on how to better teach programming. These tips, I believe, also can help you give better presentations, as well.

Building a cross-platform native app with BeeWare by Russell Keith-Magee

This was a cool one to watch. Using BeeWare we were able to see Russell show how to create, not only desktop applications, but mobile applications. This is pretty big because Python isn't known for creating mobile applications, but now that we have BeeWare perhaps it's time that it is.

Oops! I Committed My Password To GitHub by Miguel Grinberg

I'm sure we've all encountered or, at least, worried about our credentials and API keys getting checked into GitHub for all to see. Miguel talks about how to resolve it if it does happen and also goes into ways to prevent it from happening again.

Elegant Solutions For Everyday Python Problems by Nina Zakharenko

In this talk, Nina goes over several interesting Python tricks that you could use to up your Python game. Such solutions that she provides are:

  • Named tuples
  • Decorators
  • Context managers

Using Python to build an AI to play and win SNES StreetFighter II by Adam Fletcher and Jonathan Mortensen

This was a fun one to watch. Adam and Jonathan go into how they used StreetFighter II for reinforcement learning. They detail how they coded it and what they found when they first started letting the AI play the game.

The Journey Over the Intermediate Gap by Sara Packman

I'm sure we've all had some imposter syndrome at some point. Having that can hinder improving ourselves as developers. Sara goes over what she did to get out of the pleateau of stagnating at an intermediate level and offers tips on how we can do the same.

Learning From Failure: Post Mortems by Alex Gaynor

You often learn best from failure. In this talk Alex goes over that failure happens and you have to learn from it. He then goes into that one of the best ways to do that is by writting a post mortem of the project which can serve as documentation and allow others who weren't part of the project learn from it as well.

Dataclasses: The code generator to end all code generators by Raymond Hettinger

New in Python 3.7, data classes are a new way to build, well, data classes. In this talk Raymond goes over what you get when you use a data class, compares it to named tuples, and offers an example of using data classes.

Bayesian Non-parametric Models for Data Science using PyMC3 by Christopher Fonnesbeck

In this talk Christopher goes over PyMC3, a packge to build Bayesian statistical models, and how to use it to build non-parametric, or parameters that scale with your data, models.