Entries Tagged 'Python' ↓

Tab vs. Space, part XIV

So, lets say you are working in XCode 3, and you are trying to build a PyObjC app but for some reason the python code you wrote isn’t getting called.

If you are seeing weird errors in the console when you run the application (specifically “Could not connect the action <your_action> to target of class <your_AppDelgate_class>”), here’s what it probably is: In the AppDelegate python file that XCode creates it uses spaces to do the indentation of the methods.

I hail from a land where tabs are used for such tasks, and the use of spaces is look down upon in much the same way that pick ones nose in public is.

At any rate, what’s happening is when the code is compiled/run the python interpreter is not recognizing the new methods that I put in (using tabs to indent) and instead of giving me a warning about inconsistent indention, it fails somewhat silently in that it groans it can’t hook the action up to the class and that’s it. It wasn’t until I turned on the invisible characters that this occurred to me that it might be the root cause of my problems.

Once setting all of the indentions to be the same, I chose tabs, everything worked like a champ.

By the way, if you are looking for some tutorials for PyObjC in XCode 3 (there are a ton of XCode 2 tutorials out there, but things have changed ever so slightly in 3), be sure to check out these links:

Very well stated Guido!

Thanks to Reddit today, I saw this posting from Guido Van Rossum about the recent flap about the GIL in Python:

On 9/13/07, Andy Wiggin <andywiggin at gmail.com> wrote:
> I thought the discussion was very interesting. I think true parallel
> programming is the challenge of our time, so I’m quite disappointed
> that the Python powers that be do not seem to feel any imperative to
> address it. I’ve always been kind of assuming that Python would
> provide a “pythonic” parallel programming paradigm that would “just
> work” and be as elegant as the rest of the language.

I’m sorry, but this attitude just really pisses me off. Python is the
work of many people. If you want something to happen, make it happen.
Don’t wait for someone else to solve your problem for you.

–
–Guido van Rossum (home page: http://www.python.org/~guido/)

Guido is 100% right. I used to (and some times still do) sit around waiting for someone else to take care of a “problem”. That’s certainly one way to approach a problem, but it is even better if you can get into it, figure it out and produce your own solution. That is the way to truly gain new wisdom (and to learn all kinds of interesting new things).

I have discovered several times that simply waiting for someone else solve your problem is a horrible compromise to make. It usually lessens the quality of your code because the solution isn’t a perfect fit for what you are doing, and overall keeps you from gaining the true deep knowledge that is oh so helpful when debugging.

Not to mention the fact that so many open source projects have gotten their start because someone (like Guido) got tired of waiting for someone else to do something. I think its a great that Guido has been so up front with this whole GIL issue: He has said that if someone will do the leg work and prove a better way that is still backwards compatible he will welcome it. The key thing is that he said “someone” and not “I” or “me”. This encourages more people to get involved, and for a community based project/product/language, this is a great thing.

So, kudos to you Guido! Keep up the great work! And please note that I am not saying that “Not Invented Here” syndrome is the way to go, I am saying: Don’t wait for a patch, see what you can do yourself to fix it!

Pyglet

Recently I heard about pyglet which bills itself as “a cross-platform windowing and multimedia library for Python“. This is more-or-less what pygame offers, but with one exception: pyglet doesn’t depend on SDL, its written in pure python.

As a side note, if you try to install pyglet on a Mac, there is a small catch. I’m running 10.4 Tiger which uses Python 2.4. Pyglet.org does offer a dmg file to install itself, but it doesn’t work. The reason for this is that Pyglet does need ctypes, and ctypes did  not become a standard part of python until 2.5. So, to get pyglet to work on your Mac, you’ll need to get (and build) ctypes, or install Python 2.5. I installed ctypes and found it to be pretty painless.

Its still in an alpha state, but I thought it sounded interesting so I decided to take a look at it. Compared to pygame, it seems to be a little more streamlined. I’ve never really push pygame to the limits, so I can’t really compare the two as fully as I would like. One thing that I did like were the demo apps and the examples in the documentation. They were concise, yet demo’ed useful things that I would want to do in an app.

I started reading the documentation after lunch the other day and within a few minutes I found myself modifying the code as I read through the docs. Within 5 minutes I decided that I would try a sprint: Could I implement a quick and dirty game of pong within an hour using pyglet? Well, the answer is Yes!

picture-1.png

After playing around for an hour I had everything except the computer’s paddle in place working. A few days later when I had some time I spent and additional 15-30 minutes (while watching the game on TV) and knocked out the “AI” for the computer player. This isn’t award-winning code or game play (the bounding box collision test is pretty crappy), but it did show me that I could get something done quickly using this framework.

So, check out pyglet. Here’s the code to my craptacular version of pong. (There are 3 files, two images for the paddles and the ball, and the source file pyglet_pong.py)

Markov Decision Processes and the iPod shuffle

I just finished reading Peter Norvig’s article about the “Martin Shuffle“. (By the way, if you are a computer programmer, you need to visit Mr. Norvig’s site. It is chock full of good programming/lisp/algorithm stuff.) The Martin Shuffle is basically a search for a specific song by using the random shuffle feature of an iPod.

Now I know what you are thinking, but its not a crazy thing to do. In a situation where you can’t see the display or access the controls (for example with an iPod Shuffle, or when I have my iPod mini hooked up to my car stereo and I have to control it with the CD changer controls which only allow skipping and turning the shuffle on or off) this “random searching” is actually a pretty good strategy. Basically you randomly skip through songs until you get to the artist you are looking for. Once finding the artist, turn off the shuffle part and search one song at a time until you find the one you are looking for! Pretty straightforward and a fun way, well ok, a way to pass the time while sitting in traffic.

Norvig’s article talks about the math behind this type of search. Specifically he solves how long it would take to find a song (on average). He describes the problem as a Markov Decision Process that can be solved using a value iteration algorithm. Its amazing how something that sounds so complicated is actually pretty straightforward. The code that is used to implement the solution is in python and it is pretty short so it is doubly impressive, at least to me.

Getting rid of getters and setters

Today I read an interesting post about mistakes Java programmers make when they start writing Python code. The one that really caught my eye was “Don’t create getters and setters!”. Apparently a lot of other Python newbies are doing that.

I started out creating getters and setters in python a while ago and in the last month or so (while refactoring) it occurred to me that it was a waste of time since you can’t make member variables in python private like you can in Java. The more I thought about it, the more I started to wonder why I was doing straight getters and setters in Java. I mean, if all I’m doing is assigning a variable (no format checking, etc.), the having that extra code doesn’t really make much sense does it?

So, I’m on a fact finding mission to discover the what happens when getters and setters are left out in Java code and the class field is accessed directly. Yes, I know, its not OO. But if the object is just a bean and its only reason for existence is to be an member of an abstract data type (like a struct in C), then why not just let it run free? Aside from situations where you are manipulating the field in some way (like formatting, or whatnot), all the getters and setter get you is more code on the screen.

A shortfall of Python: no function overloading

I’m a big fan of Python. It has little quirks that can be annoying (like having to specify self.method() instead of using scoping rules to look at the class first), but overall I really like the language. But today I ran into a shortfall that I really stubbed my toe on: Python (as of 2.5) doesn’t support function overloading.

For example, this snippet of code won’t run:

def a():
print “This is a”

def a(x):
print “This is a(x)”

a()

Instead it will just tell you that TypeError: a() takes exactly 1 argument (0 given) presumably because the second function (a(x)) seems to overwrite the reference to the first one. Further reading on the topic shows that a fix for this might be coming in the future (see Guido’s blog entry for details).

The strange thing for me is I never noticed this until recently. The only reason I ran into it was because I wanted to do some refactoring where it made sense to have an overloaded method. Or at least that’s what I would have done in Java.

Not having this option available is having an interesting side effect in that it made me step back a little bit and evaluate the “big picture” a little bit more than I normally do. Which in this case isn’t a bad thing, hopefully it will cause some me to stretch in new directions and discover my inner OO-Architect…

Business Rules and the Visitor Pattern

One thing I really love about Python is that you can really knock things out quickly with it. I’ve been thinking about business rules lately, and specifically about how to make them cleaner with respect to your code.

When it comes to rules, there are several places and ways you can encode them in your application, each with its own pro’s and con’s. Lately I’ve been reading a lot about Lisp based languages and every now and then I’ll read a reference to using Lisp code not only as a configuration file, but as a “executable” that carries its own data.

The more I thought about this, the more I wondered if this type of separation was possible in Java. Sure, I could just code the rules in Java, but where’s the fun in that? Via its reflect package, Java can do some pretty neat tricks, so I decided to try and code up some ideas in Python first since its so concise (and can also do reflection, etc.). Basically a case of “anything you can do, I can do better”.

A while ago I read a really interesting article about the visitor pattern. Most of the time this pattern is explained in terms of something like a driver: You have some kind of hardware that needs to call a driver to setup its connection to the system. Using the accept() and visit() methods you can make a class that can register itself with the caller and allow it to configure itself, the end result being that the caller doesn’t need to know (i.e. be linked with) the details of the visitor.

It occurred to me that this is the same situation with externalized business logic: The rule engine is reading in an external file and then based on the contents of that file, executing code. If a “rule” implemented the visitor pattern, and the “rule engine” implemented the accept(visitor) method, then this would allow the external file to dictate what the program would be doing without the program needing massive changes to alter the rules.

It boils down to this: defining the core actions separately from the rules allows a better separation between  the two. The visitor pattern allows the two to be bound together. The end result is cleaner (smaller) code, that should be more “testable”. At least that’s my theory.

I’ve put the python code implementing this up on my project page (here is the code). Its a very simple example, there is one rule per line, and the first token (space delimited) is the function to call followed by its arguments. Internally the RuleEngine class is calling Python’s eval() function and that is what actually executes the function from the data.txt file.

For the function to execute successfully it needs to exist (i.e. it needs to be defined in the file, or be a built-in Python function). Note that this is not the safest approach, it will allow malicious code to execute. A more secure way to do this would be to set up a dict (or, if this is done in Java a HashMap) that contains a mapping between the rule tokens and the function to be executed. That way the execution of the RuleEngine can be controlled somewhat, in that it will only allow certain functions to be executed.

Refactoring observations

Its almost spring time and I’ve been doing some spring cleaning both at work and at home. Yes, its refactoring time.

For the most part I like refactoring. It’s a chance to go back and tighten up the code, correct earlier guesses, and just make things nicer looking. One thing that has really been hammered home to me is the type of refactoring you are trying to do depends greatly on the underlying design and what you are trying to change about it.

Example: One of my home projects is an RPG game written in python. I started out with one code base, and began changing it to meet my ideas/needs. Over time it has change two more times. Yesterday I noticed that a major class (the display that draws the tiles to the screen) had not really been migrated and could use some attention. As I began trying to work in the new changes I saw why I put the project down a few months ago: there’s got to be some major changes because the class is so different than the new architecture. As a result, most of the refactoring tools/techniques I’m used to using (at work)
just can’t be used right now.

At work, I’ve got a pretty well laid out architecture (coded in Java) and most of my refactoring work revolves around streamlining and consolidating methods and classes. The refactoring tools in Eclipse make this a breeze because everything is pretty straightforward. (Also, the strong typing of Java is really helpful in this area, its much easier for Eclipse to figure out what a member variable is in Java than it is in Python.)

The moral of the story? I think it’s best to make sure you build in some flexibility to your designs. This will allow you more choices down the road, especially as you discover new techniques for your particular language. As always, the tools are helpful, but they can only do so much to help you.

Fun with Python and Lisp

Once you fight your way through all of the junk (photo’s, xkcd comics, etc.) on reddit, you’ll occasionally find some pretty interesting and enlightening things. A few days ago I saw this link to a Scheme interpreter in Python. I’ve always been interested in the Lisp family of languages, and this is one of them implemented in python. What a cool learning experience.

After looking at that for a while I tried googling for some other examples and found this really awesome Lisp in Python implementation.

Every so often I’ll think to myself “Wow, how hard can it be to make a language?” Then I’ll remember that it can be pretty damn hard (actually I remember my Programming Languages Concepts class, then I get the shakes thinking about all of the edge cases and other complications that you have to keep track of). Seeing something like these links is really educational for me, I get to see how two similar languages have been implemented (and thanks to the comments on programming.reddit.com) and how they could have been done differently.

A wise man gets it done

Sometimes, no matter how much you whine about something, it just won’t go away until you roll up your sleeves and work on it.

I’ve been feeling like whining about how all of these cool programs and games are getting released by everybody these days, and I haven’t been able to get squat done. But every time I started to think about it, I kept remembering that I have a small pile of unfinished projects that could use some attention. Some need a little bit, others need a lot.

I’m a big fan of the “pick something small, get it working, and use that as inspiration to move onto something bigger” philosophy. I use that technique all the time at work to try and get around logjams (be they mental, or load based). For the most part its pretty effective, the feeling of accomplishment builds quickly as small tasks disappear off the old to-do list.

So I decided to apply this to a python project I’ve been twiddling with for over a year. I ran one of the tests for it, and saw an error. I spent about a half hour or so playing around fixing the error and in the process managed to improve the code flow, pretty print my output messages, and uncover a potential problem before it had a chance to bite me. And you know what? It feels good to have gotten that done. A few more sessions like this one and I might actually finish this project up before the end of the year…

As a side thought on this topic: It is really important to use tools that allow you to have a maximum amount of productivity. In a situation where you are time constrained (i.e. a deadline is looming, you only have an hour to play, etc.) every second counts. If you are fighting you IDE, you are not solving your core problems. I thought about using TextMate to try and work with my python code last night, but I kept running into situations where using Eclipse was easier. So despite the “niceness” of TextMate, I had to abandon it for this project and keep on using Eclipse (and the wonderful PyDev plugin). Less twidiling, more working.