Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Large Functions Many Variables (Refactoring)

Tags:

python

I have a large function in my script that contains the bulk of the logic of my program.

At one point, it used to span ~100 lines which I then tried to refactor into multiple smaller functions. However, I had many local variables that were eventually being modified in the smaller functions, and I needed some way to keep track of them in the scope of the larger function.

For instance, it looked like

def large_func():
 x = 5
 ... 100 lines ...

to

def large_func():
   x = 6
   small_func_that_will_increment_x()
   small_func()
   ....

What is a pythonic way to handle this?

The two approaches I can think of are:

1) global variables --- will probably get messy as I have many variables 2) using a dict to keep track of them like

tracker = {
'field1' : 5
'field2' : 4
}

and make modifications on the dict instead.

Is there a different way to do this that I might have overlooked?

like image 518
user1431282 Avatar asked Aug 16 '26 06:08

user1431282


1 Answers

Without more information, it's hard to know whether this is appropriate or not, but…

An object is a namespace. In particular, you can turn each of those local variables into attributes on an object. For example:

class LargeThing(object):
    def __init__(self):
        self.x = 6
    def large_func(self):
        self.small_func_that_will_increment_x()
        self.small_func()
        # ...
    def small_func_that_will_increment_x(self):
        self.x += 1

Whether the self.x = 6 belongs in __init__ or at the start of large_func, or whether this is even a good idea, depends on what all those variables actually mean, and how they fit together.

like image 139
abarnert Avatar answered Aug 17 '26 21:08

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!