Learning “new” features of python

I started learning python with python-2.1. Since that time a lot of features have been added. Many of those changes were well publicized: decorator syntax, context-managers, generator statements, unification of try-except-finally…. Reading the major sections of the What’s new in Python document is sufficient to call all of those out. However, there’s often other very useful changes that only get a few sentences and a bullet in the rather large list of “Other Language Changes” a the tail end of the document. It’s very easy to either miss those changes or forget about them if you don’t immediately have a use for them.

Today bochecha pointed me at one of those tiny little changes that be very useful.

I was dealing with sorting of records returned from multiple database queries. I wanted to sort the records based on date, time, and name in that order. In SQL, that would be a simple order by date, time, name but this code needed to use separate queries so I had to operate on the python list instead. No problem! Pull out the handy .sort() function and we’re all set. My code started off a bit like this:

def _get_mtg_sort_key(mtg):
    return (mtg.date, mtg.time, mtg.name)

# meetings contains an unsorted list of database records.
meetings.sort(key=_get_mtg_sort_key)

That’s pretty simple but bochecha asked why I didn’t use operator.attrgetter() instead. In my naivete I pointed out that I needed to get the values of three fields so I had to use a custom function. bochecha quickly responded that since python2.5, operator.attrgetter could handle multiple fields:

import operator

meetings.sort(key=operator.attrgetter('date', 'time', 'name'))

Although the changes here are minimal, they allow us to write something very standardized instead of an ad hoc function. That will have savings down the road when someone else needs to read the code and figure out what’s going on.

Now, this left me thinking, every new release, the python language and standard lib adds a large number of these little changes. Things like python-2.1 adding support for a tuple of type information or python-2.6 adding the httponly attribute to Cookie.Morsel objects. Anyone else have a tiny change like this that they’d like to share how they now use it to save time or make more readable code?

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s