Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python add to a function dynamically

Tags:

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?

like image 975
Timmy Avatar asked May 07 '10 14:05

Timmy


People also ask

How do you add something to a function in Python?

While defining a function in Python, you can pass argument(s) into the function by putting them inside the parenthesis. In the example above: I passed 2 arguments into the function named addNum. I told it to print the sum of the 2 arguments to the terminal.

How do you make a function dynamic in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.


1 Answers

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

like image 131
Daniel DiPaolo Avatar answered Nov 29 '22 09:11

Daniel DiPaolo