-
-
Save yashh/314040 to your computer and use it in GitHub Desktop.
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
""" | |
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