开发者

Rewrite a python script, injecting a method in each of the script's classes

Say I have a python module foo.py which contains:

class Foo(object):
    def __init__(self):
        pass

I next want to parse this script and inject a method in each of it's classes, re-writing it to something like this:

class Foo(object):
    def __init__(self):
        pass
    def my_method(self):
        pass # do some stuff here

I've noticed python 2.6 has an ast module which could be used for this, but unfortunately I need to do this in python 2.5. Any suggestions are 开发者_JS百科welcomed.


I understand what you are trying to do, but if your source code is reasonably simple, perhaps you could skip the whole parsing and writing back altogether and just run a regexp?

Something like:

re.sub('^class\s+(\w+):\s*\n', 'class \\1:\n%s' % method_source, file_source, flags=re.M)

Just get the indentation right..


Do you already have the script? You should be able to monkey patch it right now. To satisfy your current requirements, something like this would be fine:

class Foo(object):
    def my_method(self):
        pass

Alternatively, you could define my method and add it to the Foo class as an attribute:

def my_method(self):
    pass

Foo.my_method = my_method
#or
Foo.__dict__.my_method = my_method


A solution would be:

class Foo(object):
    def __init__(self):
        pass

import new

def some_func(self):
    print "foobar"

Foo.my_method = new.instancemethod(some_func, None, Foo)

The problem is, I don't like appending the new method definitions at the end of the file. I would like the classes in generated script to look like:

class Foo(object):
    def __init__(self):
        pass
    def my_method(self):
        print "foobar"

but can't find a solution to this without building, modifing and then writing back a sintax tree.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜