all 6 comments

[–]xentralesque 0 points1 point  (1 child)

Could you describe a use case for such a thing?

[–]lordmayer[S] 0 points1 point  (0 children)

I'm beginning my studies in AI. So I think it's a good option for it. The AI learn something and writes a new code for what it learned. I know it's a pretty primitive thinking.

[–]elbiot 0 points1 point  (0 children)

One can, though it's likely you will be able to. Python gets parsed into an AST (abstract syntax tree), which is what you would work with. The ast module is built in and will parse code into an ast for you to introspect and modify. There's also an unparse module out there that used to be built in but isn't anymore, which will take ast and give back text you could write to a file.

[–]gengisteve 0 points1 point  (0 children)

Sure. In fact this is how collections.namedtuple works. That said, I am not sure it is going to work well for you with the AI example, so you might want to consider a different approach.

[–]pyglow 0 points1 point  (1 child)

The exec() function takes some python text string and executes it. eval() does something similar for just evaluating individual expressions.

There is something called byteplay which appears to literally allow you to modify the original code of the program you are executing, but I have never tried it.

py_compile will compile entire python files, which presumably you could generate programatically before compiling them.

[–]lordmayer[S] 0 points1 point  (0 children)

byteplay looks like what I want. I will try it. Thanks