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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With