Faking Ruby blocks in Python


Ruby has a construct called "block" that enables a programmer to define a block of code and pass it to a method. This construct comes handy whenever you want to do something on a block of code but you don't want to put it to a separate function. Consider, for example, how tedious it would be if you would have to define a separate function for every while, for, or if statement, instead of putting the code in a block immediately following the control statement, such as in the following example. [sourcecode language="python"] def block_of_code: <instructions>

if(condition, block_of_code) [/sourcecode]

The closest equivalent in Python to Ruby blocks are lambda functions, but with important distinction that lambda functions are (intentionally) limited to one line of code. But since blocks are merely nameless methods that you can pass to other methods, there exists a trick using decorators how to have blocks also in Python.

Take for example that for some reason you'd like to have an infinite_loop construct in Python. One way how to implement it in the style of Ruby blocks is as follows

[sourcecode language="python"] @infinite_loop def _(): <your instructions> [/sourcecode]

where infinite_loop decorator is specified by

[sourcecode language="python"] class infinite_loop: def __init__(self, function): while True: function() [/sourcecode]

Using decorators as an approximation for Ruby blocks in Python is possible because the __init__ constructor for the decorator is executed at the point of decoration of the function.

I googled for other solutions how to fake Ruby blocks in Python, but I couldn't find any. If you know of one yourself, let me know in the comments. And if you like this construct, maybe we can petition Guido to include in the future extensions of Python the following construct

[sourcecode language="python"] @decorator: <your instructions> [/sourcecode]

that would enable decorating also an anonymous block of code, not just of a named function.