Skip to content

Instantly share code, notes, and snippets.

@msabramo
Created October 24, 2011 23:23
Show Gist options
  • Select an option

  • Save msabramo/1310716 to your computer and use it in GitHub Desktop.

Select an option

Save msabramo/1310716 to your computer and use it in GitHub Desktop.
Ruby-style blocks in Python
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