Reflecting and Modifying Python Code

Perhaps I am not using the correct term, but I want to take a block of Python code (in Python), get a marker tree for the code, make some kind of modification and reassemble it in Python.

For example, consider this block of code:

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

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

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

I cannot imagine that there is no library that does something like this. Thanks in advance.

EDIT

, . , , . . , , : Netflix, , . , , / .

+3
4

, , Apalala, :

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)

:

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

, , . , , , , .

+2

Python , , - :

def x(fx, y):
    b = 2
    if y == b:
        fx(y)

:

x(foo, y)

x(bar, y)

, (v 3.1), - bizlogic, :

def x(fx, y): return fx(y)
def foo(x): return x
def bar(x): return x+1

print(x(foo,1))
print(x(bar,1))

:

>>> 
1
2
+1

, :


    class A(object):
        def __init__(self, x):
            self.x = x
        def show(self):
            print self.x

    def chglobals():
        import newmod
        reload(newmod)
        o = newmod.A(0)
        globals()['A'] = o.__class__

    def main():
        a = A(10)
        a.show()

        #change and wirte new code
        src = inspect.getsource(a.__class__)
        src = src.replace("print self.x", 'print "foo" ')
        text_file = open("newmod.py", "w")
        text_file.write(src)
        text_file.close()
        chglobals()

        #new istances
        b = A(20)
        b.show()

        #convert old istances
        a.__class__ = b.__class__
        a.show()


    main()

0

, , . , , . :

def foo(x): return x
def bar(b): return x+1
fn = { 'foo': foo, 'bar': bar }

def x(y):
    b = 2
    func = 'foo'
    if y == b:
        fn[func](y)

, , . , func (, "bar" ).

-1

Source: https://habr.com/ru/post/1787028/


All Articles