How-To

Quick and dirty prototyping

Quietly, under the cover of darkness and the Business of Software forums, I've been spreading the corrupting CodeSnipers influence to pull more people into the inner circle. I'm honored to have our latest victim aboard. The author of Agile Project Planning... Dave Churchville. - Editor.

"Just tell me what you want and I'll build it!"

What programmer hasn't uttered those fateful words? The problem is that even though users often know what problem they have, they are rarely the best people to tell you how to solve it.

Enter the prototype. Developers either hate them or love them, depending on their experience. If you've ever built a sophisticated prototype that faithfully re-created the entire application, only to have it forced into production, you probably hate prototypes. Or worse, maybe no one even bothered to look at it!

Case Study - Car Webcam

Have you ever said to yourself, "Wow, if I only had a webcam in my car..."? No? Me neither, but it might be a fun exercise to explore anyway. We'll leave it to the marketers to figure out how to sell it, right?

What this project is going to need:

  • One car
  • One laptop
  • One webcam
  • One mobile Internet connection

Lambda at Work

Lambda
Finally, several years after learning lambda expressions, I got a chance to use one at work a few days ago. As long as I'm putting a notch in my nerd belt, I'd like to write about what lambda is and how it can be useful.

A lambda expression defines an anonymous function. Here's a regular function definition:

def inc(x):
    return x + 1

This definition binds the name inc in the local namespace to a function object. To get the exact same functionality using lambda, assign the lambda expression to a variable:

inc = lambda x: x + 1

A lambda has two parts: the argument list (only one arg in this case) before the: and an expression after. It can't contain statements (like assignments or print) because it's an expression itself. This is a pretty useless example, so let me show how I used it today.

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
True
>>> 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:

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:

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.

Looping
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..

Hi Ho Silver! Away!

Remember the Lone Ranger? Believe it or not, I actually watched it as a kid. I don’t know why he was called the Lone Ranger, he always seemed to have Tonto - his Indian sidekick with him. Often, I code alone (I thought about rewriting the "I Drink Alone" song to "I Code Alone" but I had only had 1 small cup of coffee when I wrote this) and I’ve been thinking of some "tricks" to help me with my lonely quest.

Say Hello to My Little Friend

With my recent Ruby on Rails project, I've done more on the linux command line than with PHP development. For example, you run a ruby script to generate a code skeleton for scaffolding, controllers, models and views. Stuck with a windows environment for my development on the go (I commute 3 hours a day, in which time I'm hacking away on my laptop, which I am doing right now. In Vim.)

I reached into the crevices of my mind to remember how to create Batch files. Yes, that’s right, batch files. Yes, Good Old MS-DOS. I still have a DOS For Dummies book (aquired long after DOS was out, I just couldn't resist the nostalgia and I think it only cost 2 bucks). I created a batch file for ls, mv and cp. Not rocket science I know and although I had installed cygwin I was not particularly keen on using that all the time, I also had found some exe's that imitate many of the unix commands...but I didn't need all that jazz. I just wanted a ls, mv and cp command!

As my project progressed, I was doing more and more on the server side, tweaking here and there. Man, I said… I need to get VI for windows I knew it existed, I had it many years ago. Actually, I think it was only a dos version that I had. I searched and discovered GVIM. And it’s pretty darn nice!

Using Live Clipboard, part 1

Last week, I was talking about Live Clipboard, and how it was well worth investigating. Now I’m taking a closer look at the technical introduction, to see how it works, and find out how easy it is to add to a page.