You are viewing benno37

Ben - Python decorators

May. 4th, 2005

04:18 pm - Python decorators

Previous Entry Share Next Entry

I love Python because it is so easy to write unreadable code in.

I wanted to handle sub-commands and didn't want to go to all the hassle of
maintaining a dispatch dictionary. So I decided I could be really seedy and
do:

globals()[args[0]](args[1:])

However this sucks if someone picks function that wasn't intended as a subcommand.

Python decorators to the rescue! My main problem with the dispatch dictionary was
having to update commands in two places. So with decorators I can do this:

commands = {}

def command(fn):
commands[fn.func_name] = fn

@command
def foo(args): pass

and then

commands[args[0](args[1:])

and I don't have to be so seedy. Of course I'm sure people still won't understand
what I'm doing, but thats ok ;)

Comments:

[User Picture]
From:wzdd
Date:May 4th, 2005 01:23 pm (UTC)
(Link)
I still reckon you should use it. I've got Python 2.4!
[User Picture]
From:inhahe
Date:July 5th, 2005 05:53 pm (UTC)
(Link)
I'm looking all over, trying to figure out what the Heck Python decorators do. I still don't get it. :/