python, saving changes made to an imported module
I have a situation where users can pick another method from another clases and use it in thier own class using the .im_func. i give an example below
import foo1
import foo2
foo1.ClassX.methodX = foo2.ClassX.methodX.im_func
Where methodX could be implemented differently in both modules.
When i instantiate the object say foo1.Class(), methodX from module
foo2` is used.
My problem is ho开发者_如何学Cw to save the changes made maybe as foo3.py to a new source code file.
saving it as new py could be a problem but you can easily use serialization for it (pickle module)
see: http://docs.python.org/library/pickle.html
The source code can be retrieved with inspect
module. However, the problem with that is, that it's the original source code, not source code of dynamically modified object.
Have you considered using parser combined with the aforementioned inspect to do this? In this situation it might be better to simply go with text processing rather than attempting to use imported modules.
EDIT: An example of using the parser to print the file:
with open('foo1.py','r') as fh:
st = parser.suite(fh.read())
src1 = parser.st2list(st)
with open('foo2.py','r') as fh:
st = parser.suite(fh.read())
src2 = parser.st2list(st)
You'd have to then do some tricky programming to merge the methods from the source code and write it to a file. But then again I have the strange feeling I'm not quite understanding the question...
精彩评论