I have encountered a problem in python for which I have yet to find a suitable design pattern. Generally, the following code exhibits the issue:
#large number of variables
a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
h = 8
i = 9
j = 10
#complicated computation
#logical grouping 1
a = ...
b = ...
c = ...
d = ...
e = ...
#logical grouping 2
f = ...
g = ...
h = ...
i = ...
j = ...
print a + b + c + d + e + f + g + h + i + j
#simplified using functions
def func1():
global a, b, c, d, e
a = ...
b = ...
c = ...
d = ...
e = ...
def func2():
global f, g, h, i, j
f = ...
g = ...
h = ...
i = ...
j = ...
func1()
func2()
print a + b + c + d + e + f + g + h + i + j
In this minimal example, I have a large number of integer variables on which I would like to perform some complicated mathematical calculations. To simplify the calculations, I would like to place them inside functions, as I have been taught to do. Because python resolves naming conflicts in favor of the local scope, however, I am forced to declare all the variables I will work with in the function to be global. I realize that this is a minor inconvenience, but when I change what a function does or how my program stores data, I need to also change the global variables declaration at the beginning of the function. This can easily lead to difficult-to-track-down errors (no compile or runtime errors, but a variable won't change when I think that it should), and it just feels like bad design.
In short, the inconvenience posed by python's treatment of scope makes me disinclined to break my code into functions, as I understand to be best practice. Specifically, my question is two-fold: why does python behave in this way, and what is the design pattern that should be applied in a case such as mine?
Note: I would assume that these questions have mostly objective answers. If they do not and someone with more knowledge than me believes that they will only lead to discussion and voicing of opinions (which I understand is against SO policy), then I will happily find a more appropriate forum for this question.
Aucun commentaire:
Enregistrer un commentaire