2

To understand what I'm asking let's take an example:

I have a method (this function is not mine) m is declared in a class c. This method contains about 200 lines. I just want to add an element to the list which is declared inside the function.

   class c(object):
        def m(self):
            .....
            .....
            .....
            ls = [1,2,3]
            for l in ls:
                 ......
                 ......
                 ......
                 ......

My problem is the list should be [1,2,3,4]. I don't want to copy the whole code of the method just to change the ls variable and this method is not mine so if there are some updates later I want to use them.

I tried to see how Python saves the local variable in the function object and I didn't understand how the relation is set.

# this tuple is so complicated 
m.__code__.co_consts

So is there an easy way to update this variable, or do I have to update it to add an element to the list by analyzing the variable and see where to put the 4 element?

I searched a lot for this problem but I only found a way how to override a inner method (the answer belongs to @Martijn Pieters):

Override inner method

So is there an easy way to just change a variable without having to rewrite the whole code?

1 Answer 1

3

You cannot change that variable inside that method. You need to change the method where it is defined.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.