samedi 2 juillet 2016

Python Large Functions Many Variables (Refactoring)

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?

Aucun commentaire:

Enregistrer un commentaire