The BDFL has already weighed in on anonymous blocks in Python:
If you want anonymous blocks, by all means use Ruby. Python has first-class callables,1 Ruby has anonymous blocks. Pick your favorite, but don’t whine that neither language has both. It ain’t gonna happen.
do_something_asynchronous(param1, param2, (def callback(result): do_something_with_result(result) ))
for item in results: (def single_iteration(): do_something_asynchronous(param1, item, (def callback(result): do_something_with_result_and_item(item, result) )) )(item)
I’ve even had occasion to want that other Python namespace,
class, to operate as an r-value:
class MyConverterClass(BaseConverterClass): my_converter_type = (class MyConverterType(float): def __str__(self): # a custom __str__ method return '%0.2f' % self )
In these examples I’ve wrapped their inline definitions in Python’s great syntactical equalizer, the parenthesis. It would be even nicer to be able to leave them off, but I’m sure that this syntax would run headlong into Python’s whitespace-based block definitions, and it would be even more of a train-wreck without parentheses.
I’ve also named the
lambdas, are the electric third rail of Python syntax, so anonymous classes would be… I dunno, the nuclear fourth rail?
- Thanks to Steve for explaining that by “first-class callable,” GvR means functions that can be passed around and assigned to other variables without being executed. He also pointed out that the reason Ruby’s callables aren’t first-class is because optional parentheses in function calls leave no way to refer to a function without calling it, not because of the existence of anonymous blocks. [↩]