Gabriel
Gabriel

Reputation: 42329

Pass variables between functions vs global variables

I have a code with several functions defined which I call from a main container code. Each new function uses variables obtained with the previous functions, so it looks kind of like this:

import some_package
import other_package

import first_function as ff
import secon_function as sf
import third_function as tf
import make_plot as mp

# Get values for three variables from first function
var_1, var_2, var_3 = ff()

# Pass some of those values to second function and get some more
var4, var5 = sf(var_1, var_3)

# Same with third function
var_6, var_7, var_8, var_9 = tf(var_2, var_4, var_5)

# Call plotting function with (almost) all variables
mp(var_1, var_2, var_3, var_5, var_6, var_7, var_8, var_9)

Is this more pythonic than using global variables? The issue with this methodology is that if I add/remove a new variable from a given function I'm forced to modify four places: the function itself, the call to that function in the main code, the call to the make_plot function in the main and the make_plotfunction itself. Is there a better or more recommended way to do this?

Upvotes: 0

Views: 141

Answers (2)

abarnert
abarnert

Reputation: 365627

What about putting them in a class?

class Foo(object):
    def ff(self):
        self.var_1, self.var_2, self.var_3 = ff()
    def sf(self):
        self.var_4, self.var_5 = sf(self.var_1, self.var_2)
    def tf(self):
        self.var_6, self.var_7, self.var_8, self.var_9 = tf(self.var_2, self.var_4, self.var_5)
    def plot(self):
        mp(self.var_1, self.var_2, self.var_3, 
           self.var_5, self.var_6, self.var_7, self.var_8, self.var_9)

foo = Foo()
foo.ff()
foo.sf()
foo.tf()
foo.plot()

Maybe some of these methods should be module-level functions that take a Foo instance, maybe some of these attributes should be variables passed around separately, maybe there are really 2, or even 4, different classes here rather than 1, etc. But the idea—you've replaced 9 things to pass around with 1 or 2.

Upvotes: 1

Philip Kendall
Philip Kendall

Reputation: 4314

I'd suggest that what you want is a data structure which is filled in by the various functions and then passed into make_plot at the end. This largely applies in whatever language you're using.

Upvotes: 0

Related Questions