Created
October 24, 2011 23:23
-
-
Save msabramo/1310716 to your computer and use it in GitHub Desktop.
Ruby-style blocks in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class EvalBlock(object): | |
| def __init__(self, code_string): | |
| self.code_object = compile(code_string, '<code>', mode='eval') | |
| def __call__(self, *args, **kwargs): | |
| return eval(self.code_object) | |
| class ExecBlock(object): | |
| def __init__(self, code_string): | |
| self.code_object = compile(code_string, '<code>', mode='exec') | |
| def __call__(self, *args, **kwargs): | |
| return eval(self.code_object) | |
| # Because we can't add methods to int in Python | |
| class NumberObject(int): | |
| def times(self, block): | |
| for i in range(0, int(self)): | |
| block(i) | |
| def upto(self, upper_num, block): | |
| for i in range(int(self), int(upper_num)): | |
| block(i) | |
| # Because we can't add methods to list in Python | |
| class ListObject(list): | |
| def collect(self, block): | |
| ret = [] | |
| for item in self: | |
| ret.append(block(item)) | |
| return ret | |
| NumberObject(5).times(ExecBlock(""" | |
| print "%d - %s" % (args[0], args[0] * '*') | |
| """)) | |
| NumberObject(1).upto(5, ExecBlock(""" | |
| print "%d - %s" % (args[0], args[0] * '*') | |
| """)) | |
| ret = ListObject([1, 2, 3]).collect(EvalBlock("args[0] * 2")) | |
| print "result of collect => %r" % ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment