Python code reflection and modification
Question: Perhaps I'm not using the proper term, but I'm looking to take a block of
Python code (in Python), get the token tree for the code, make some kind of
modification, and re-assemble it to Python.

For instance, consider this block of code:

    
    
    def x(y):
        b = 2
        if y == b:
            foo(y)
    

I would like to be able to take this and programmatically do this:

    
    
    def x(y):
        b = 2
        if y == b:
            bar(y)
    

I can't imagine that there's not a library that does something like this.
Thanks in advance.

**EDIT**

Perhaps I wasn't entirely clear. I'm looking for a tool to read and manipulate
_arbitrary_ code, not code that I'm writing. I'd like to be able to modify
code on-the-fly. The project I'm working on is a test app: it uses the
[Netflix philosophy](http://www.readwriteweb.com/cloud/2010/12/chaos-monkey-
how-netflix-uses.php) to try to randomly break the functionality of an app in
as many ways as it can, running the test suite each time. When the tests don't
fail, there's an indication that there's either a gap in code coverage and/or
the code is dead.


Answer: I was curious about this so I looked into the link Apalala posted, here is
what I came up with:

    
    
    from token import NAME
    from tokenize import generate_tokens, untokenize
    from StringIO import StringIO
    
    source = """def x(y):
        b = 2
        if y == b:
            foo(y)"""
    result = []
    tokens = generate_tokens(StringIO(source).readline)
    for toknum, tokval, _, _, _ in tokens:
        if toknum == NAME and tokval == "foo":
            tokval = "bar"
        result.append((toknum, tokval))
    
    print untokenize(result)
    

And the result is:

    
    
    def x (y ):
        b =2 
        if y ==b :
            bar (y )
    

Yeah I know, the spacing is ugly. I could not figure out how to maintain the
format from the original code, but as far as functionality goes, this does
what you want.

