10.18
This might be a somewhat unorthodox usage of python decorators, but a very practical and nice one – I got a question on IRC from a friend that wanted to store python functions in a dictionary and was complaining that there is no way to use lambdas in python as anonymous closures because of their limitations and the syntax of: def func(): pass; dict["func"] = func; is ugly, and I agree – so here’s a nicer version utilizing an extension of the built in dict-class:
class MyDict(dict):
def __call__(self, func):
self[func.__name__] = func
foo = MyDict()
@foo
def bar(arg):
print "from bar %s" % arg
foo["bar"]("Hello World!");
The idea and usage is simple: Extend the built in dict class with a subclass that is turned into a decorator, this decorator then stores every function it decorates inside it’s own dictionary.
Simple, practical and elegant.

No Comment.
Add Your Comment