I wanted to know if it would be possible in some way, during execution, to modify a function.
At first it seems to me that it is not because it is already compiled. At most I can get the function code object __code__
or use inspect.getsource()
to view it. But what I would like to do is change the body of a function from a text string entered through a shell.
Depending on what you want to support as a text string, the solution could be
eval()
orexec()
.eval()
allows you to evaluate expressions, but not arbitrary python code. Insteadexec()
it does allow arbitrary code.Consider the following example:
In this case the user must comply with what is expected of him, which is a function definition called
funcion_usuario()
. If you want you can make the user enter only the body of the function, and you can concatenate in front of it the line ofdef
(and indent what the user entered).Needless to say, this is highly dangerous , as the user can enter arbitrary python code instead of a function definition, eg
os.remove("fichero_importante")
.