Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 welcomed.

like image 985
Ioan Alexandru Cucu Avatar asked Oct 17 '25 16:10

Ioan Alexandru Cucu


2 Answers

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..

like image 188
Gurgeh Avatar answered Oct 20 '25 06:10

Gurgeh


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
like image 42
Tim McNamara Avatar answered Oct 20 '25 05:10

Tim McNamara