Search code examples
pythonglobal-variables

"Global variable" in multiple functions


I am trying to collect data with a global variable, without returning the variable

def collect_result(result):    
    is_global = "Res_collected" in globals()
    if is_global == False: 
        global Res_collected
        Res_collected = []
    elif is_global == True:
        Res_collected.append(result)
    return

How can I use or call this variable in another function?


Solution

  • You don't need to do anything special in order to read the value of a global variable inside another function, you can just refer to it by name, so print(Res_collected), for example.

    If you want to write to the global variable, you would do that in the same way you're already doing it in your collect_result function, by using the global keyword. This is a decent introductory tutorial.

    As others have already pointed out, it's generally not a good idea to use global variables. A better alternative is to pass your collection of results as a parameter to whatever functions are going to use them. That way it is clear and explicit what data is being read or modified by each function.

    Global variables can hide important clues about what data is being used, where and how, which makes the code harder to understand, and can lead to other problems further down the line.