if __name__ == ‘__main__’ can be nicer!

After many times of writing out this default “main” code, I decided to work out if there is a way that I don’t have to type as much and make it look nicer. Yes, I’m pedantic with code neatness. Here is an example of what I’m talking about:

def main():
    print 'this runs only when executed directly'

if __name__ == '__main__':
    main()

I asked on Stack Overflow, but the general answer was “deal with it”. After a quick discussion of the problem, @dsturnbull and myself worked out that it was possible to import a module and use a decorator in place of this if statement.

The module is called automain, and here is an example of its usage:

from automain import *

@automain
def main():
    print 'this runs only when executed directly'

I threw it on github, and Python Cheese Shop and it can be easy_installed:

easy_install automain

How does it work?
The source code of the decorator looks like this:

def automain(func):
    import inspect
    parent = inspect.stack()[1][0]
    name = parent.f_locals.get('__name__', None)
    if name == '__main__':
        func()

Basically it inspects the parent stack frame, and checks if __name__ is ‘__main__’, then executes the function. Otherwise it does nothing, as expected.

Internet Trolls
Interestingly enough, a random internet troll rated the module 0/5 on Python Cheese Shop and started his comment with:

spookylukey (2011-01-24, 0 points):
Seriously? Is this a joke?

1. Your implementation can’t possible work – it is going to do the same if the module is imported as a library or if it is run as a script.
[..snip..]

All I have to say is that it does work and I find it much better to use. Thanks for the terrible and incorrect feedback though, spookylukey!

What is the longest word you can type with one hand?

I was looking for random, useless facts on the Internet the other day and found one that said:

“Skepticisms is the longest word that alternates hands when typing.”

This turned out wrong. A friend convinced me to write an application to work it out, and I decided to make it do more…

The application uses the UNIX words file to scan for words. Granted, not all the words actually are real, but it is a good indication.

To cut to the chase, the longest words with one hand on the QWERTY keyboard layout are 12 letters long:

aftereffects, desegregated, desegregates, reverberated, reverberates, stewardesses

These are all left handed words. In fact, there are 57 longer words that can be typed than the longest right handed word. The longest right handed word is “polyphony” with 9 letters. I found this a bit unusual so I decided to graph it (below). With alternating key strokes, the longest words are:

authenticity, enchantment, entitlement, proficiency, shantytowns

These are 12 letters for authenticity and 11 for the rest.

Here are the graphs for QWERTY with left vs right vs alternating sides:

I recall that the Dvorak Simplified Keyboard was designed with alternating hand key strokes in mind. With alternating sides, the highest word count is 14–slightly more than QWERTY’s 12. These words are:

overemphasized, overemphasizes, unpremeditated, verisimilitude

Interestingly enough, the Dvorak layout has very few words that have multiple key presses on the same side of the keyboard. The left side is the most popular with the longest words, at 6 letters, being:

kookie, opaque, papaya, upkeep, yippee, yuppie

The right side has a lowly score of 3 letters, one isn’t even a word:
brr, nth

Here is the Dvorak graph:

Well, come to your own conclusions from this data! I was just curious and slightly bored…

The graphs are made with Google Charts API using the pygooglechart module. If there’s enough interest I’ll throw the code up on github.

Creating an OS X Installer for Python modules and extensions

In the past, people have hassled me to make it easier for them to install my applications and libraries on OS X. I’m not very skilled with OS X, and searching for how to do this task took some time. I’ve made a script that does this in a modular way for Python. Specifically, this article describes the process of making a Python module or extension installer for OS X, similar to the Python installer for Windows.

Continue reading Creating an OS X Installer for Python modules and extensions

Python Google Chart 0.2.1 released

I just released pygooglechart 0.2.1. It has several bug fixes and minor additions, but the major change is that it now supports QR codes. You can quite easily create a QR code with pygooglechart as you can see below.

from pygooglechart import QRChart

# Create a 125x125 QR code chart
chart = QRChart(125, 125)

# Add the text
chart.add_data('Hello, World!')

# "Level H" error correction with a 0 pixel margin
chart.set_ec('H', 0)

# Download
chart.download('qr-hello.png')

This will download a png from the URL:

http://chart.apis.google.com/chart?cht=qr&chs=125×125&chl=Hello%2C%20World%21&chld=H|0

The image downloaded looks like this:

QR codes are new to me. I’ve only seen a QR code on a bus stop advertisement once in Sydney but I’m sure more will pop up.

Wireless Heatmap

Update: WiFi Heat is available on the Google Play Store! For more information, see http://wifiheat.com/.

I wrote an application to generate a wireless (802.11) heat map based on signal strength. The reason for it was to find the best place/area (for my laptop) to be with the highest signal strength. Below is a screenshot of the application (with the ESSID and BSSID removed for security reasons).

This heat map has about 100 samples in it, which are shown as white dots. There is a balcony at the top of the image and the common office area on the right, which was drawn by hand (hence the waviness). As you can see it has pinpointed the location of the access point in the red area.

Continue reading Wireless Heatmap

Create a fast C Python extension with Cython tutorial

Cython is an easy way to create Python extensions in “pseudo-Python” without having to deal with the verboseness of the Python API. It also does not rely on you knowing much of the C language. Cython is based on Pyrex which I have some experience with. This tutorial shows you how to convert a simple Python module to a Python extension.

Continue reading Create a fast C Python extension with Cython tutorial

TracRecaptchaPlugin 0.1.0 – A CAPTCHA plugin for Trac

I decided to make a CAPTCHA plugin for Trac called TracRecaptchaPlugin, to stop spammers using the ticket system. There is an existing Trac plugin to fight spammers, but it still lets through many automated spammers.

The plugin uses the reCAPTCHA service and is serving me well so far. Here’s how it looks within the template:

TracRecaptchaPlugin Screenshot

This is my first publicly released Trac plugin so I’m unsure how it’ll perform out there, so feedback is welcome.

A fast Python vector class

Since completing the first version of Roids, I decided to get right into optimisation. After running the Python profiler, I noticed my vector class was taking a long time in __getitem__, so I did some tests. It turns out that __getitem__ is extremely slow compared to direct attribute access. For example in some cases I was using pos[0], pos[1] instead of pos.x, pos.y. By using attribute access, it yielded approximately an 8-10 time improvement over __getitem__. I quickly removed any reference to this!

I became curious about what else I can improve, I tested the time difference between creating an old-style class and a new-style class. It turns out that new-style classes are created 1.5x faster then old-style classes.

An Old-style class looks like this:

class Vec:
    def __init__(self, x, y):
        self.x = x
        self.y = y

New-style classes look like:

class Vec(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

There was another test I did, which was using __slots__. By defining a list of attributes you will be using in your class, a new-style class will not create a __dict__ object for the class. This decreases the time it takes to create an instance of the class by a slight amount (13.6% in my tests). Here is an example:

class Vec(object):
    __slots__ = ('x','y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

One final test was using a list as a base class instead of just using object. For example:

class Vec(list):
    def __mul__(self, o):
        return vec((self[0] * o, self[1] * o))
a = vec((1.0,2.5))

This was about 20% slower then my new-style class using __slot__.

Overall these changes improved the speed of Roids quite substantially. After all that, here is the fast Python vector class.

Note: These tests were run on a Pentium 4 running Windows XP with Python 2.4.2. Since I’m only testing on one platform these results may vary for you. I plan on testing these on other computers and operating systems soon.

40 hour python multiplayer game challenge

After 6 days and 40 hours I managed to make a simple multiplayer game called Roids. On the surface it looks like another Asteroids clone but it is a litte more then that. At the moment Roids has two teams with players that fly around just like the original Asteroids, but one player on each team can become a RTS player. It was written in Python so it runs a little slow and will be improved over time. The version released was 0.0.1 and I’ll be working on it for the next few weeks.