Archive for June, 2008

Dynamic Method Creation in Python

Monday, June 30th, 2008

I like to use this example to totally freak out Java people. Cool dynamic languages such as Python or Ruby allow you to modify the definition of any class on the fly. Javascript let’s you do that too, but then again Javascript does not really have classes right now. It’s a prototype based language – at least until ECMAScript 4 descends from heavens in a beam of heavenly light and will bring forth much awesomeness. Here is how you do it in Python:

Observe:

>>> class Person:
...     def __init__(self, fname, lname):
...             self.fname=fname
...             self.lname=lname
...
>>> john = Person("John", "Smith")
>>>
>>> Person.whatisyourname = lambda p: "My name is " \
...     + p.fname + " " + p.lname
>>>
>>> john.whatisyourname()
'My name is John Smith'

Every new instance of Person will now have a whatisyourname() method. C and Java people are probably sneering right now, at how insecure this is, how it breaks encapsulation and etc. I used to be like that too, but I reformed. What I see here is raw power.

I’m putting this here because I was trying to do closures in Python but found out you can’t really do them. Python has lambda functions instead which are really a lisp concept. The only difference between a Python lambda function and a closure is that lambda must evaluate to something. In other words, it’s body must be an expression rather than a statement. Which makes perfect sense in Lisp because it has no statements. In Lisp everything is an expression – and frankly, that is not a bad idea. Lets you chain stuff pretty nicely.

If you need to use Python statements however, you can’t use lambda. You just have to use regular assignment:

>>> def foo(self):
...     if(self.fname < self.lname):
...             print "foo"
...     else:
...             print "bar"
...
>>> Person.foo = foo
>>> john.foo()
foo
>>> zack = Person("Zack", "Abrams")
>>> zack.foo()
bar

Of course the downside here is that this is not a closure, and that the method definition exists outside the class on its own which can contribute to clutter in your code. Then on the other hand, perhaps this isn’t so bad as it allows you to do stuff like:

>>> foo(john)
foo
>>> foo(zack)
bar
>>> foo = Person.whatisyourname
>>> foo(john)
'My name is John Smith'

I guess that’s part of Python’s charm that standalone functions can easily become instance methods and instance methods can be easily used as standalone functions.

Dexter: Season 2

Friday, June 27th, 2008

When I blogged about Season 1 of Dexter I expressed my concern about quality of the second season. Really good shows which deliver a satisfying conclusion in it’s first season’s finale can often suffer from a sudden drop in quality. I felt that this is what happened to Heroes. I lost interest around episode 3 or 4 of the second season, but kept watching until around episode 10 hoping they will find the spark back. They didn’t. At some point I will need to go back and find out how that season ended, but I’m no longer addicted to that show.

vlcsnap-3314065-custom.JPG

Dexter avoided this fate. In my honest opinion second season actually raised the bar a little bit. The story arc seemed to be more tightly woven. We delve even more deeply into Dexters past and explore his relationships, and see him make difficult choices. The whole season is built around the age old formula of taking a likable character, and then systematically ruining his life, relationships, shaking his belief system and making him question all the values he lived by until now. As the FBI launches a full blown investigation against him, discovers a new way to deal with his dark urges. But this new path leads him to question the code of Harry, jeopardizes his relationship with Rita and leaves him emotionally vulnerable. It is a rolercoster ride from the beginning to the end – and a masterfully written and executed one at that.

vlcsnap-3315051-custom.JPG

I believe that the writers decided to take the show in a completely different direction in this season, and it has very little in common with the second book. But since I didn’t read any of the Dexter novels, they get the benefit of the doubt. I liked this story arc, and I thought it tied in with the events of the first season very well. Since I enjoyed it so much, I will simply choose to believe that the choices they made were correct ones considering the overall differences and departures from the original that they accumulated in the first season. If you think otherwise, please feel free to correct me. I won’t argue against it, since I don’t really know much about the plot in the books.

vlcsnap-3315696-custom.JPG

Just like the first, the second season is a complete chapter and the last episode wraps up all loose ends. In fact, it does a better job of it than the S1 finale. There were still some unresolved issues that the final episode did not answer. This time around, Dexter’s universe gets almost rebooted back to the point where he can start with a clean slate, and a new perspective on life, and his role in the natural order of things. The ending of course implies that Dexter’s story will continue, but leaves absolutely no clues as to what is next in store for him. It really left me wondering what the hell will they do in season 3. They did such a great job at turning Dexter’s life upside down this time around, that they left almost nothing for future use. In season 1 we dealt with a serial killer who knew Dexter’s secrets, and directly threatened his loved ones. In S2 we are dealing with a full blown investigation, an identity crisis, and relationship problems. All of these things get resolved in a satisfying way. Any future threats to his loved ones, possibilities of being discovered or romantic issues may seem like a rehashing material from the previous seasons. So what is left? What is the next big thing that will shake Dexter’s life, and keep us glued to the TV for the next 12 episodes? I was concerned about quality of S2. Now I’m terrified about the quality season 3. I’m afraid that any direction they take from here will seem like nothing more than cheap re-packaging of already explored themes and topics. Keeping the show interesting and addictive will be a true test of skill for the writers. Can they pull it off? I believe they can! I hope they can. But only time will tell.

I don’t think I can say more about the season without letting out huge spoilers. So I won’t. It’s suffice to say that it is good, and that I loved it. If you enjoyed the first 12 episodes, you won’t be disappointed.

Google App Engine

Thursday, June 26th, 2008
Google App Engine

When the Google App Engine first launched I didn’t really have much to say about this. It was neat but I failed to fully comprehend what it represented. Only after I read a transcript of Steve Yegge’s recent talk in which he briefly mentioned it I realized the significance of this service. It was really an off-hand comment but something just popped in my head the moment he mentioned it. Which is not surprising at all:

croppercapture77-custom.jpg

Btw, I just wanted to mention that Google App Engine and Google Apps for Your Domain are really heading for a branding conflict. Not even the Google search engine itself can easily distinguish between the two. One ought to be renamed at some point to spare users the confusion.

But why is this service interesting? It gives us a brand new hosting model. You want to build small, throw away web applications? Look no further – all you need is a valid Gmail account and some knack for Python scripting. That’s all. No configuration, no maintenance, and no hassle – you even get a free subdomain at appspot.com.

In the past you really just had to buy yourself some hosting space. There was no way around it. In most cases you ended up with a heavy duty plan with your own domain name, lots of space, a full LAMP stack (or something equivalent that needs to be maintained), ssh access and various other benefits. Often an overkill and and a considerable investment both time and money wise for what you might have needed.

Google on the other hand provides you with a basic environment that’s relatively easy to pick up, and lets you start hacking immediately. It is a bit like what Geocities was to us in the early days of the web – a free hosting where anyone can put their personal web app. Especially if you don’t want to pay a monthly fee because you are broke, or because your parents won’t let you use their credit card to buy hosting. It’s a place for young and inspired teenagers, or lazy and bored developers with a cool idea but no inclination to host and maintain. The mundane details are abstracted – you don’t need source code repository, because each time you deploy Google stores a copy of your old code so that you can roll back.

You don’t need to worry about database specific stuff – like setting up users, connecting to the db and etc – it’s all built in, automated and behind the scenes. It’s actually even easier than in RoR where you still have to create a database configuration file, build migration files and then “rake” them. Google App Engine just requires that you import the db module, and write a Model class specifying data types for the fields you want to store – right there in your code. And the fun part is that you can modify your data scheme by just modifying the code. On top of that you get a neat web interface letting you maintain and browse through the stored data.

You don’t need to worry about authentication scheme since you can just drop in Goggle’s authentication instead. This way they store the passwords, and they are responsible for making things secure and efficient. Implementing these an authentication scheme yourself is always a hassle – so “outsourcing” it this way is generally a good idea – especially for small projects, or when you are feeling lazy.

Getting dugg, or DDOS’ed (aren’t the two the same though?) is no longer your problem, but Google’s problem – and they are pretty good at load balancing throttling and dealing with situations like that. The scalability of Google App Engine can actually be a major draw – for anyone. For example, Jaiku – a somewhat popular twitter clone is migrating to the Google App Engine platform for that very reason: scalability. This move will allow them to concentrate on delivering value to end users via new features and bug fixes rather than fighting a constant logistical battle trying to build up their infrastructure to handle ever increasing server load. It’s not an easy battle to win, as Twitter users can attest to. Scaling up is arguably most expensive, and most labor intensive element of running a popular web application. If Jaiku can offload this cost onto Google they gain an important advantage over Google.

So Google is offering us is a really powerful and versatile package, and it’s free. All you need to do is create an account and start hacking. If you look through their app library you will see all kinds of interesting ideas popping up. Some are big apps like Jaiku, and some are small hobby projects. Out of the latter my favorite must be the TweetWheel. Just try it and see that it is an interesting concept, but not really something you would actually want to pay for hosting.

This is a profound step toward increasingly more complex scriptable server side systems. It will never really replace traditional hosting. Since Google App Engine is a sandbox environment, a lot of apps would be simply impractical or inconvenient to run there. But it offers a new compelling new alternative for established applications, startups and small hobby projects alike. But it is more than that. This is an experiment in allowing users run and host their code on your servers.

We all know that moddable and scriptable systems are valuable because community that grows around them adds immense value. Look at Firefox for example – with millions of extensions and add-ons that do everything from checking your email to playing music. Some are actually incredible paradigm breaking ideas such as Greasemonkey which allows you to inject your own Javascript into a page while it is rendered allowing you to control it’s layout and even add features never considered by creators. This is the type of creativity that can be spurned only by a fully scriptable system. If you want another success story look at Emacs – a text editor which started as very basic text processing engine, and grew into a monster that we know and love today.

So scriptable and moddable applications on the desktop are good thing. And we pretty much figured out ways to make sure scripts and mods can’t totally break your app – at least not easily. We also know that moddable web applications are great too – everyone loves Twitter apps, Facebook apps and Google maps mashups. These are great examples how community can add to a great service. This is why every service which wants to be popular creates a public API. But, if you want to write a facebook app, or a twitter app or something like that you have to host it somewhere. And your hosting plan must be robust enough to survive a sudden spike in popularity. I have seen many a Facebook app go under or become unusable because their servers could not handle the load. And this is a problem – not everyone can afford to have a dedicated server just to host an add-on for a popular online service.

This is the problem that Google App Engine solves. They are the few companies out there which figured out how to safely let people run arbitrary code on their servers without getting pwned by script kiddies. They have found a way to safely, securely and efficiently sandbox user created web applications from the rest of their system. And this is huge. It is a proof of concept that this sort of thing can be done, and it can be done safely.

The implication of this experiment is that people can now start building extendable systems which not only expose a public API but will host and maintain user-submitted add-ons making them much more reliable responsive and flexible. After all, if you are hosting the app there is no reason to communicate via XML, JSON or whatever your public API is using. You can simply let users call a function and return an object they can manipulate eliminating the overhead of TCP/IP transmission and serializing/serializing data. I don’t think anyone is doing that yet, but Google App Engine is a first step in that direction. In the future we can see a brand new species of online services – ones that grow and transform themselves and adopt allowing the vibrant community to add new features and modules. Picture this: an emacs like flexibility and malleability, but for a web service. This could be huge…