0

This is a follow up question to the last question I'd ask, which you can read here:

Using Python's basic I/O to manipulate or create Python Files?

Basically I was asking for the best way to allow Python to edit other Python programs sources, for the purpose of screwing around/experimenting and seeing if I could hook them up to either a genetic algorithm or some sort of backprop network to get results.

Basically, one of the answers suggests making every python operator or code-bit, such as '=', 'if', etc, etc, into classes which can then be used by me/various other programs to piece together/edit other python files, utilizing Python's basic file i/o as a means of manipulating.

The classes would each, upon initialization, get their own unique ID, which would be stored, along with line number, type, etc, in an SQLite3 database for logging purposes, and would be operated upon by other classes/the basic file i/o system.

My question is: Is this a sane task? If not, what can I change or do differently? Am I undertaking something that will be worthwhile, or is it completely idiotic? If you need clarification please ask, I want to know if what I'm doing seems reasonable to an outside source, or if I should reconsider/scrap the whole deal...

Thanks in advance.

Community
  • 1
  • 1
Aaron Tp
  • 353
  • 1
  • 3
  • 12
  • What are you trying to achieve, eventually? – uselpa Jul 07 '12 at 08:25
  • I just wanna see if I can get the basic operators hooked up to a genetic algorithim of sorts or some janky sort of backpropogation algorithim to get results... – Aaron Tp Jul 07 '12 at 18:46

1 Answers1

0

Don't generate code modify the AST for the code.

import ast
p = ast.parse("testcode")

Docs for AST: http://docs.python.org/library/ast.html

Example of modifying code: http://docs.python.org/library/ast.html#ast.NodeTransformer

Example: (modifying 3*3 to 3+3)

from ast import *
tree = parse("print(3*3)") #parse the code
tree.body[0].value.args[0].op = Add() #modify multiplication to plus
codeobj = compile(tree,"","exec") # compile the code
exec(codeobj) #run it - it should print 6 (not 9 which the original code would print)

BTW, I am interested in genetic algorithms. If you start a project, I can help you.

Ramchandra Apte
  • 4,033
  • 2
  • 24
  • 44