Thursday, August 29, 2013

Python: dicts vs. classes

I like to "keep it simple stupid" when I'm coding Python. I use classes, but I don't try to shove everything into classes. When all you need is a dict or a list, use a dict or a list. However, I'm coming to think that if you have a bunch of objects that look like the following:

books = [{
  "authors": ["Neil Gaiman"],
  "title": "American Gods",
  "isbn": "9780062113450"
}]

Then it might be time to use a class rather than a dict. In this case, I'd create a class called Book, but I'd put Book instances into a simple list.

Wednesday, August 28, 2013

Python: One More Example of How PyCharm is Psychic

I had the following line in my Python code:

if self._lookup_unallocated(current_allocation_state, key) > 0:

I wanted to change it to:

unallocated = self._lookup_unallocated(current_allocation_state, key)
if unallocated > 0:

Hence, I highlighted the expression, right clicked, refactor, extract, variable. It did the refactoring and automatically guessed that I wanted to name the variable "unallocated"! Presumably, it guessed based on the name of the method I was calling. Nonetheless, it's like it read my mind!

Friday, August 23, 2013

Python: Using assertRaises as a Context Manager

If you're using the unittest library, and you want to check the value of an exception, here's a convenient way to use assertRaises:

with self.assertRaises(ValueError) as context_manager:
    call_some_function()
self.assertIn("Oops, something went wrong", str(context_manager.exception))

Thursday, August 22, 2013

Humor: Testing the Validity of Internet Email Using Perl

My wife sent me an email yesterday. It said, "What the :_&#/_&/#=;$ is he doing with a 28 year old! That is sick :-(". I wanted to test the validity of her statement, so I fed that expression into Perl. Perl ended up spitting out the first 10,000 digits of Pi. Go figure.

Monday, August 19, 2013

Books: Treading on Python

I just received my copy of Treading on Python! I was the technical editor :) There are two things that are great about this book. First, Matt Harrison's a really good Python programmer, and his writing is very crisp. Secondly, the book is really short! It's weighs in at a mere 183 pages!

So if you're reading this, Matt, congratulations, and thanks for letting me part of your book!