Search code examples
python-3.xfunctionvariables

how to update local variable(s) in a called function as the function arguments in python?


If you create local variable(s) in a function, and then calls a function with those variable(s) as argument(s). How do you update the value of the variable(s) so it reflects in both functions?

disclosure:

  • The called function is a segmented piece of the main body of code for tidiness and reduce code repetition. The called function is only called under conditional circumstances and doesn't necessarily return anything. All it does is some calculation that updates the values of variables passed within the function arguement.

How would you get the values in function 2 to update the same values as in function 1?

Thank you in advance!

for example:

def function_1():
    object_1 = 1
    object_2 = 2

    function_2(object_1, object_2)

    print("Original values add up to {}".format(object_1 + object_2))

def function_2(object_1, object_2):
    object_1 += 1
    object_2 += 2

    print("Updated values add up to {}".format(object_1 + object_2))

if __name__ == '__main__':
    function_1()

Updated values add up to 6
Original values add up to 3

Solution

  • Option 1: return the updated values to the calling function

    def function_1():
        ...
        object_1, object_2 = function_2(object_1, object_2)
        ...
    
    def function_2(object_1, object_2):
        ...
        return object_1, object_2
    

    Option 2: build a data structure in function_1() (like a dict for example, or a list or a custom class) and then pass that as the argument to function_2(); the changes to the dict you make inside function_2() will be reflected in function_1(), because it is the same dict, you just passed a reference to the same dict as argument between functions.

    def function_1():
        ...
        data = {'object_1': 1, 'object_2': 2}
        function_2(data)
    
        # the variable 'data' contains the changes made in 'function_2()'
        print(data)
        ...
    
    def function_2(data):
        # the variable 'data' points to the same dict as in 'function_1()'
        data['object_2'] += 55
        ...
    

    There could be other options I am not thinking of right now, but these 2 are the simpler ones, I think.