Search code examples
pythonglobal-variables

How to access a variable outside of a function (access from a loop)?


I am working on accessing a variable outside of a function. Here is part of my code:

def main():
    trigger_gmm() = 0
    log = []
    def spatter_tracking_cb(ts, clusters):
        global trigger_gmm
        for cluster in clusters:
            log.append([ts, cluster['id'], int(cluster['x']), int(cluster['y']), int(cluster['width']),
                        int(cluster['height'])])
             if cluster['width'] >= 200:
                 trigger_gmm = 1
             else:
                 trigger_gmm = 0
             print(trigger_gmm)
while True:
    print(trigger_gmm)
    if trigger_gmm == 1:
        print("print something")

if __name__ == "__main__":
    main()

I get the output like this:

NameError: name 'trigger_gmm' is not defined

Any ideas would be much appreciated!


Solution

  • You have three issues in that code:

    1. trigger_gmm() = 0 - You need to remove the parenthesis
    2. You need to move the global variable definition up to the beginning of the main function
    3. The if __name__ == "__main__": is not reached as it is after the while loop, you need to move it up.

    EDIT: I added a global declaration to the main module (above the main function) and inside the spatter_tracking_cb function. This is because you need to indicate that the variable trigger_gmm is a global variable whenever you use it.

    This code seems to work for me:

    global trigger_gmm
    
    
    def main():
        global trigger_gmm
        trigger_gmm = 0
        log = []
    
        def spatter_tracking_cb(ts, clusters):
            global trigger_gmm
            for cluster in clusters:
                log.append([ts, cluster['id'], int(cluster['x']), int(cluster['y']), int(cluster['width']),
                            int(cluster['height'])])
                if cluster['width'] >= 200:
                    trigger_gmm = 1
                else:
                    trigger_gmm = 0
                print(trigger_gmm)
    
    
    if __name__ == "__main__":
        main()
    
    while True:
        print(trigger_gmm)
        if trigger_gmm == 1:
            print("print something")