Nate Silva

Nov 07 2007

Notes on using Cocoa-Python in Mac OS X Leopard

I’ve been looking at Leopard’s amazing new Cocoa-Python support. It uses PyObjC 2.0 to give Python programmers access to the Cocoa frameworks that Mac OS X is built on.

Working from the Apple tutorial, which is based on an older version of PyObjC, I was able to build a working application. But I hit a few roadbumps and those are what I want to document here for other would-be Cocoa-Python programmers.

The first problem was figuring out how to instantiate my Averager object in Interface Builder. I found the solution on the macosxhints Forums:

  1. Drag an instance of NSObject from the Library into your xib file.
  2. Click on the new instance of NSObject and bring up the Identity Inspector (⌘-6 or find it in the Tools menu).
  3. Set the object’s class name to your class name, which is Averager if you’re following the Apple tutorial.

The second problem was this error:

This class is not key value coding-compliant for the key calculatedMedian

This was caused by not importing the Averager class. To fix it, add the following to your main.py file:

from Averager import *

Some tips:

  • The debugger console window (Shift-⌘-R) is your friend.
  • Beware of Xcode’s tab handling. You can force it to use spaces under Preferences > Indentation.
  • If you are doing the tutorial and you get “ValueError: invalid literal for float()”, it’s because you’ve passed something that doesn’t look like a number — most likely a comma. Python’s split method only recognizes lists separated by spaces. In the debugger console you can see what exception is raised. You can of course catch the exception and handle it in your Python code.

Page 1 of 1