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?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Charif DZ
  • 14,415
  • 3
  • 21
  • 40

1 Answers1

3

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

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662