Monday, May 11, 2009

Python 3.1 - get ready

Python 3.1 is in beta testing now. The changes can be found here, but I'll post a quick summary:

Ordered dictionaries: Example 29 provides us with a SortableDict class, found in the collections module. What Python 3.1 gives us is a little different, though. It just keeps the order that you passed in the items. In addition to all of the normal dict methods, this new class has a method OrderedDict.popitem(last=True) that will pop the last (or first, if last is set to False) item off of the object, much like list.pop(). Note that if you change the value of an item, the order will not change. If you remove that item and then add it back in, the item will then go to the back. Here's how to use the OrderedDict class in 3.1 (using Dr. Punch's example29.demo() example values):

And the output...








String formatting, the new way. As you probably have read in my first post, the format method on strings is the preferred way to format strings... but it seems kind of silly to number each format part if you're just going in order (like we're used to with the % operator):
"I asked my friend {0}, and I asked my friend {1}; they said it was {2}!".format("Joe", "Jake", "fhqwhgads")
Well now, with Python 3.1 (RC1 is out), you can do this:
"I asked my friend {}, and I asked my friend {}; they said it was {}!".format("Joe", "Jake", "fhqwhgads")
and you will get the same formatted output. Of course, the numbering method will still work (and is still necessary if you want to be playing with the order of the format strings).

Also format-related, check this out (the comma means to add decimal separators, everything else has been around since 2.6/3.0... "0" says the first argument to format, ":" means to do manipulation, ".2" means 2-precision, "f" means to "coerce" to float):
>>> "{0:,.2f}".format(123456789)
'123,456,789.00'

That's right, human-readable decimals with string formatting!
(Combine this new change with the previous one and you get this:)
>>> "{:,.2f}".format(123456789)
'123,456,789.00'

More to come when I get time.