Search code examples
sublimetext2sublimetext3sublimetextsublime-text-plugin

Re-assign global variable


How I can update variable globvar from 0 to 1?

import sublime_plugin

class TestMe(sublime_plugin.EventListener):
    def on_activated(self, view):

        globvar = 0          # The goal is to update this var from 0 to 1

        def updateme():
            global globvar
            globvar = 1

        def printme():
            print(globvar)

        updateme()
        printme()            # It *should* print 1

This code snippet (all credits to Paul Stephenson) should print 1. And actually it works when I test it in online Python playgrounds, for example here.

But for some reason, in Sublime (ST3 build 3126) it prints 0. Very strange. How it could be fixed?


Solution

  • Your problem isn't that this works differently in Sublime, it's that what you have written is semantically different than the example code you based this on.

    In your code example, globvar isn't global; it is a variable local to the on_activated method.

    When you say global globvar in the updateme function, you're telling python that accesses to globvar should be to a global variable and not the one that it can currently see from the local scope, which causes it to actually create a global variable with that name and use that instead.

    For you this means that the updateme function is creating a global variable and setting its value to 1, but the printme function is printing the local version of the variable, which is still at 0, so that's what you see.

    For the variable to actually be global, you need to move it outside of the method, to the top level of the module file:

    import sublime_plugin
    
    # Out here the variable is actually "global"
    globvar = 0
    
    class TestMe(sublime_plugin.EventListener):
        def on_activated(self, view):    
            def updateme():
                global globvar
                globvar = 1
    
            def printme():
                print(globvar)
    
            updateme()
            printme()            # Now prints one