Archives: 'code'

Optional arguments in Python

Friday, March 7th, 2008

Optional arguments in python are obviously very useful allowing you to have default values so you don’t need to pass them every time. A simple hello world example always goes a long way…

def hello(to="world"):
    print "Hello,", to
>>> hello("Steve")
Hello, Steve
>>> hello()
Hello, world

Sometimes you’ll see people define an optional argument with a default value of None then override it in the function’s body. This might seem a strange thing to do at first, but there is a reason. Let’s say that we wanted to be able to say hello to a list of people and for it to automatically add “World” to the list.

def hello(to=[]):
    to.append("World")
    if len(to) > 1:
        greeting = "Hello, " + ", ".join(to[:-1]) + " and " + to[-1]
    else:
        greeting = "Hello, " + to[0]
    print greeting
>>> hello(["Steve", "Matt"])
Hello, Steve, Matt and World
>>> hello(["Steve", "Matt"])
Hello, Steve, Matt and World
>>> hello()
Hello, World
>>> hello()
Hello, World and World
>>> hello()
Hello, World, World and World

This happens because the value for the default argument is the same list every time, so when we modify it the function has the same modified list as the default argument when it is subsequently called. This is probably not the behaviour you would expect and you would rarely want to use this behaviour. The way around it is to define the default argument as None then override it.

def hello(to=None):
    to = to or []
    to.append("World")
    if len(to) > 1:
        greeting = "Hello, " + ", ".join(to[:-1]) + " and " + to[-1]
    else:
        greeting = "Hello, " + to[0]
    print greeting

>>> hello()
Hello, World

>>> hello()
Hello, World

>>> hello(["Steve", "Matt"])
Hello, Steve, Matt and World

>>> hello(["Steve", "Matt"])
Hello, Steve, Matt and World

Because None evaluates to false, setting the default value to None means it can be easily overridden to give us the default value we actually want if there wasn’t a passed value.

Python Webcam Time Lapse Script

Friday, February 24th, 2006

I have written a Python script to download a webcam image at a configurable interval. I am currently testing it with the BBC’s three Aberystwyth webcams. Although it should work with almost any webcam. I will use these images to make time-lapse style video.

The script uses the If-Modified-Since and If-None-Match headers in the GET request to ensure the same image is not downloaded twice. The script is capable of regularly downloading images from several webcams. I will be using either ffmpeg or mencoder (from the mplayer project) to create the videos.

Thanks to Matthew Russell (aka horizon5) for help with threading. Thanks also to Gary Steele for his page on creating videos from a series of images.

For those who want to run it themselves, I’ll put it online in a few days to download once I know it works properly and the code is tidied up a little.

Irssi Scripts

Tuesday, February 7th, 2006

I recently switched to using the Irssi IRC client from XChat. Because the scripts and commands I had become used to in XChat are not available for Irssi I wrote a couple of scripts for Irssi.

Mass Op (/mop) command for Irssi - A script which gives everyone ops on the channel except for people who have “voice” (+v).

XMMS Currently playing script - Says to the channel what you are currently listening to something like

[music | Jefferson Airplane - White Rabbit (Surrealistic Pilow)]

when you enter /xmms

Google-it - A script that says to the current window a url to “Google It, You Moron” based upon specified keywords. For example

/google irssi scripts

produces

http://www.googleityoumoron.com/?go=irssi+scripts

Read this if you don’t know how to use irssi scripts.

Last.fm musical taste overlap

Wednesday, November 30th, 2005

I have written a short Python script to allow you to find the overlap between the favourite artists of two user’s on Last.fm.

For example, my Last.fm favourites compared to my friend Seb’s favourites currently produces this list.

swp1@flemensfirth:~/src/python/lastfm-intersect$ python pair.py Aimaz cybersebb
In Flames
Pantera
Black Sabbath
Led Zeppelin
Dead Kennedys
Opeth
Beastie Boys
Anathema
Pink Floyd
Queens of the Stone Age
Iced Earth
Rage Against the Machine
Metallica
My Dying Bride

You can download the script here.

I am working on another script to do a similar thing for a group of people, but it needs to be programmed differently, otherwise given a large enough list of users no artists would appear in the list.

My GreaseMonkey scripts

Wednesday, September 7th, 2005

I have been getting quite into making GreaseMonkey scripts. If you don’t know what GreaseMonkey is it’s a firefox extension that allows you to use javascript to modify any website you like. I have been reading an excellent online book ‘Dive Into Greasemonkey‘ by Mark Pilgrim in order to learn how to make decent scripts. I have since been uploading the scripts to my userscripts.org profile.

So far I have only put two scripts on, but I think they’re pretty nifty for a beginner :). First is ‘Google Media Search‘ which adds links to google that quickly add the search terms neccesary for finding media directories online.

The other is a modification to an existing script that adds text links to The Pirate Bay and Torrent Reactor from Last.fm to allow single clicking to search for an artist. I changed it to use icons instead of text links and to open the links in a new firefox tab.