mallipeddi (owner)

Forks

Revisions

gist: 313423 Download_button fork
public
Public Clone URL: git://gist.github.com/313423.git
Embed All Files: show embed
rubycodeblocks.py #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
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) + " ")
 

Web annotations