Search code examples
pythonmetaprogramming

Python add to a function dynamically


how do i add code to an existing function, either before or after?

for example, i have a class:

 class A(object):
     def test(self):
         print "here"

how do i edit the class wit metaprogramming so that i do this

 class A(object):
     def test(self):
         print "here"

         print "and here"

maybe some way of appending another function to test?

add another function such as

 def test2(self):
      print "and here"

and change the original to

 class A(object):
     def test(self):
         print "here"
         self.test2()

is there a way to do this?


Solution

  • You can use a decorator to modify the function if you want. However, since it's not a decorator applied at the time of the initial definition of the function, you won't be able to use the @ syntactic sugar to apply it.

    >>> class A(object):
    ...     def test(self):
    ...         print "orig"
    ...
    >>> first_a = A()
    >>> first_a.test()
    orig
    >>> def decorated_test(fn):
    ...     def new_test(*args, **kwargs):
    ...         fn(*args, **kwargs)
    ...         print "new"
    ...     return new_test
    ...
    >>> A.test = decorated_test(A.test)
    >>> new_a = A()
    >>> new_a.test()
    orig
    new
    >>> first_a.test()
    orig
    new
    

    Do note that it will modify the method for existing instances as well.

    EDIT: modified the args list for the decorator to the better version using args and kwargs