Python Flyweights

I mentioned at the end of my post on Python Equality that another way to solve the example given was to use the flyweight pattern. I gave code for playing cards that would end up with many small duplicate objects in memory, and that memory usage can be reduced if (as in the example) the objects don't have extra state that wasn't used for testing equality.

Let's look at the final version of the Card class and its usage again:

values = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
suits = ('h', 'c', 'd', 's')
class Card:
    def __init__(self, value, suit):
        self.value, self.suit = value, suit

    def __repr__(self):
        return "<Card: %s%s>" % (self.value, self.card)

    def __eq__(self, card):
        return self.value == card.value and self.suit == card.suit

    def __ne__(self, card):
       return not self.__eq__(card)

>>> c1 = Card('J', 'h')
>>> c2 = Card('J', 'h')
>>> c1 == c2
>>> id(c1), id(c2)
(-1210559028, -1210558804)

As designed in the previous blog post, two different objects (as seen by their different ids) equate because of the custom __eq__() handler.

But this is a bit silly -- Cards are so small and simple, having identical objects is wasteful. If we're writing the code for a casino, we don't really want several thousand Jacks of Hearts, we want many references to one object. The idea is that instantiating a Card object checks a hidden pool of objects for a duplicate and returns it, creating a new object only if needed. (Code based on that of Duncan Booth.)

import weakref

class Card(object):
    _CardPool = weakref.WeakValueDictionary()

    def __new__(cls, value, suit):
        obj = Card._CardPool.get(value + suit, None)
        if not obj:
            obj = object.__new__(cls)
            Card._CardPool[value + suit] = obj
            obj.value, obj.suit = value, suit

        return obj

Notice that this uses new-style classes. (Side note: I cringe at anything named "new", "next", "updated", etc. because they tell me nothing. If the only thing you can say about a reimplementation is that it's not the old one, put down your copy of Refactoring and back away from the computer. Take up writing toothpaste advertisements.) If you're wondering what's up with __new__, Guido explains the difference best:

__new__ is the first step in instance construction, invoked before __init__. The __new__ method is called with the class as its first argument; its responsibility is to return a new instance of that class. Compare this to __init__: __init__ is called with an instance as its first argument, and it doesn't return anything; its responsibility is to initialize the instance.

The other possibly-unfamiliar element is the WeakValueDictionary. In a nutshell, it's a dictionary that deletes its entries if no other variables point to them. When instantiating a Card object, it checks in the Card class's _CardPool to return an existing object, or creates a new Card object if needed.

If you're confused, take a few minutes to play with the code. Insert print statements into __new__ to show you the contents of _CardPool.items() and whether a new object is created. There's a lot of important object orientation concepts at work in a short block of code: inheritance, the difference between classes and objects, references, and overriding.

I've removed the __eq__ and __ne__ calls because two Cards with the same value and suit are the same objects, saving our casino many gigs of precious RAM:

Micro ISV: From Vision to Reality, Bob Walsh interview on

PerlCast is not just about Perl! Josh McAdams interviews Bob Walsh, author of the book Micro ISV: From Vision to Reality. In it he talks about the definition of a MicroISV, gives advice on starting, marketing and dealing with hostile customers among many other topics.

For a chance to win a copy of the book, see the PerlCast site for instructions on how to enter AND see a transcript of the interview.


If you are not familar with PodCasts, they are simply mp3 files you can play on your PC or any portable device, they are not just for iPods! A transcript is available on the site if you prefer not to listen.

DC PHP Conference - Announcement and Call for Papers

PHP in the Federal Enterprise and the World:  Secure Solutions for Federal Agencies, IT Companies and Non-Profit Organizations

We are hosting the first DC Metropolitan area PHP Conference this October.  Not only that, but since we're in a unique location with opportunities and potential impact like nowhere else in the world, we're taking a slightly different look at PHP. Our mission is to demonstrate and teach how PHP is a solid, sensible, cost-effective, and low risk development language to use for government and non profits.

Therefore, our Presentation Tracks fall into four areas:

  • Integrating PHP with Federal Operations and the Enterprise
  • Security & Accountability
  • The Art of PHP
  • The Business Case for PHP

The Call for Papers ends on July 7th and gives suggested topics in each of these areas.  Your presentation will be up to 400 people including decision makers for some of the largest and most influential organizations in the world.

Ketchup on Rusty

Spring has hit Seattle like a damp blanket. It's better than the 30-days-of-rain from January though, and people are finally getting the moss scraped off their backs. The days are actually light for over 12 hours now, the grass is growing (I've mowed thrice!), and all manner of creatures great and small are crawling and flying.

At the onset of every winter, I say to myself, "This winter I am going to use my gloomy days off and dark week nights to ________," and by this time every year I have done none of it and wonder where the winter went.

One winter a few years ago, I was going to get abs that I could see. That didn't, and still hasn't, happened, although I am in fair shape. Every winter for the past 10 years I've determined that I was going to pass the Microsoft certification exams. I don't even remember why I wanted to do it in the first place, but I've intended to do it for so long now that it is something that just has to get done (I hope that will put it to rest even though MS changes the certification levels every three years).

Equality for Python

A few days ago in #chipy, the chat room for the Chicago Python Users Group, we had a chat about how Python determines equality. It's a pretty neat and extensible technique, so I'm going to walk through how I recently used it for playing cards.

Here's the basic Card class. Note that I'm going to totally skip things like error-checking and documentation to keep the example obvious.

values = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
suits = ('h', 'c', 'd', 's')

class Card:
    def __init__(self, value, suit):
        self.value, self.suit = value, suit

    def __repr__(self):
        return "<Card: %s%s>" % (self.value, self.card)

Man, does code get short when you don't bother checking for errors. The usage is pretty clear, but there's one odd issue:

work, work and life balance

I have been quiet here for the last couple weeks, more a reader than a writer. For me one of the more interesting articles of late was Wife of the mISV - Surviving the Business. When I showed it to my own wife, we shared a laugh and a moment of knowing silence - yeah, this one hits home.

Imagine the following. You're working as a software engineer on some pretty deadline-driven projects. You typically have a lot to do during the regular 9 to 5, enough in fact that you've been known to bring some of it home over the weekend, you know, just in case you got some downtime. You have got a significant other and your combined schedules are such that both of you are really always looking forward to the weekends, when you are both available at least most of the time.

Then, an opportunity turns up. One involving work and circumstances that make it very intriguing for you. The only caveat: The way to make it work is to do both jobs together for a while. Your dayjob (telling yourself, not to bring work home anymore on the weekends) and then the new job, on contract-basis in the evenings and weekends. What would you do? And for how long?

More VIM tricks

Since my post a few weeks ago, I've been using VI when developing and I only need to access one file, if I need to be workin with multiple tabs at once then I use UtraEdit.(I wrote a review here).

Comment a block of code
I learned this from my friend Brian... say you have 5 lines of code you want to comment out, perhaps you are doing caveman debugging to find where the real problem is..

ctrl-v to go into visual block mode
j down to select the first column in each line
I to insert at begining of line
enter your comment symbol

And there you go! Thanks Brian :)

VIM does orgami
Almost, although you can't make a paper crane with VIM, you can fold your code to make long chunks of code easier to live with. This is something I use in UltraEdit, when I have a really looooooong function that I am not curently working with and I have to scroll up and down to see the code around it.

Learning Design Patterns – Iterator Pattern

This week I'll be stepping through the Iterator Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
The Iterator Pattern encapsulates the functionality for stepping through a collection of items. The iterator object implements the stepping; the aggregate itself does not step through its own collection.

The pattern generally has a few of methods like first(), hasNext(), Next(), isDone() in some combination. In some programming languages it is possible to step through an iterator using a For Each item in Aggregate....<code>....Next type of construct.

Where is it used?
Anywhere there is a group of items. An array list is a common example; an iterator would step through the array items until the end of the collection was reached.

PHP can be cool like Ruby

All the cool kids these days are using Ruby...however I am stuck in a PHP world at the moment. I've been doing Ruby on some side projects and its got me thinking in a ruby mindset...and I wonder.. can PHP do that? And I've found a few things that might make a PHP geek's life a bit easier or at least PHP a little more tolerable.

Yes yes, the good old for loop.

for ($i = 1, $i <= 10; $i++) {
    print "Processing $<br>";

The simple act of doing something 10 times. Ugly huh? He's one way to do it in Ruby..