Skip to content

Instantly share code, notes, and snippets.

@mallipeddi
Created February 24, 2010 13:34
Show Gist options
  • Save mallipeddi/313423 to your computer and use it in GitHub Desktop.
Save mallipeddi/313423 to your computer and use it in GitHub Desktop.
"""
Emulating Ruby-style code blocks in Python.
This example was demonstrated in the PyCon'10 talk titled "Python Metaprogramming".
"""
import sys
import types
def receive_block(func):
def wrapped(*args):
if len(args) == 1:
block = args[0]
instance = None
elif len(args) == 2:
instance, block = args
# Add block to func's scope
scope = func.func_globals
scope.update({'block':block})
# create a new func with the new scope
new_func = types.FunctionType(func.func_code, scope)
if instance:
return new_func(instance) # return the method
else:
return new_func() # return the function
return wrapped
# Goal - mimic the following Ruby code
# [1, 2, 3, 4, 5].each( |x| print x**2, " ")
class Array(list):
@receive_block
def each(self):
for i in self:
block(i)
a = Array([1,2,3,4,5])
@a.each
def _(x): # this is the anonymous code block
sys.stdout.write(str(x**2) + " ")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment