jtcnw
jtcnw

Reputation: 101

Inject some code in the middle of the Python function

Is there any way to inject some code in the middle of the Python function before specific operation?

E.g. this is my function:

def my_function(myList):
   myList.append(3)
   myList.remove(4)
   myList.append(5)

and I need to inject (e.g. using decorator) additional operation before remove operation. Is it possible?

Thanks

Upvotes: 1

Views: 172

Answers (1)

David Camp
David Camp

Reputation: 340

You could try adding the operations in a list and then calling all of them in your function:

operations = [
    lambda x: x.append(3),
    lambda x: x.remove(3),
    lambda x: x.append(5),
]

def my_function(myList):
    for operation in operations:
        operation(myList)

Now if you want to inject an additional operation into your function, just add it to operations:

new_operation = lambda x: x.append(4)
operations.insert(1, new_operation)

Upvotes: 1

Related Questions