Ian Bicking: the old part of his blog

Playing with decorators and blocks

This is really just a silly use of decorators to do something vaguely like Ruby's or Smalltalk's blocks:

def collect(sequence):
    """
    Like Ruby's .collect::

        >>> @collect([1, 2, 3])
        ... def result(item):
        ...     return -item
        >>> result
        [-1, -2, -3]
    """
    def decorator(func):
        return [func(item) for item in sequence]
    return decorator

Someone must have done this before. But then decorator abuse is still young, so maybe not. I wrote up a few examples: foreach, inject, and file_do. Also a decorator set, which lets you add methods to classes and objects, like:

>>> class color: ...
>>> @set(color)
... filter(self, r, g, b):
...     return self.__class__(self.r*r, self.g*g, self.b*b)

And then your color class gets a new method filter. It can also add methods to objects, but you have to do @set(color_instance, make_method=True). Hmm... but now that I think that it would be neater if it looked at the name of the first argument to the function, and turned it into a classmethod staticmethod (or did nothing and left it a normal method); or if attaching it to an instance it would bind the class or instance to the first argument. So, magic_set is in there too.

They are in http://svn.colorstudy.com/home/ianb/ruby_blocks.py

Created 04 Mar '05