In Python nothing is truly “global” in the traditional sense of the word, in that it doesn’t escape outside of the confines of the current file (module) without someone taking explicit action to try and get at it. Even then, the name would be qualified with the name of the module that it came from, and the module would be qualified by the name of the package that the module is in.
So basically there are none of the usual concerns about collisions with other similarly named variables in other places unless someone goes out of their way to try and break things.
For the specific case of Sublime plugins, when your plugin modules are loaded by sublime it invokes the dir
function on the loaded module to find all of the symbols it contains and ignores everything that’s not a subclass of one of the special plugin classes (i.e. ApplicationCommand
, WindowCommand
, TextCommand
, EventListener
and ViewEventListener
).
As such, so long as your helper classes are not subclasses of one of those classes, you pretty much have free reign to do as you please from within your own plugin files.
If you’re not familiar with how this sort of thing works in Python as opposed to other languages, the syntax and semantics might be a little “weird” initially, but I think that’s about the only caveat. The only other thing I can think to point out is that you have to be aware of the ramifications of using the global, but it sounds like you are.
Symbols with a single leading underscore (e.g. _myValue
) and those with two leading underscores and no more than one trailing underscore (e.g. __myValue
) have some special semantics, but for your use case here that doesn’t really matter. This page talks about that a little.
A simplistic example of doing something like this, based on what you outlined above:
import sublime
import sublime_plugin
_myGlobal = None
class MyClass():
def __init__(self, value):
self.value = value
class MyCopyCommand(sublime_plugin.WindowCommand):
def run(self):
global _myGlobal
self.window.run_command("copy")
_myGlobal = MyClass(sublime.get_clipboard())
class MyPasteCommand(sublime_plugin.TextCommand):
def run(self, edit):
sublime.set_clipboard(_myGlobal.value)
self.view.run_command("paste")
def is_enabled(self):
return _myGlobal is not None
The important takeaway is that the “global” is really just a top level symbol in the module.
Anything that wants to read the value (in this case everything in MyPasteCommand
) can just do so with no special syntax. When the access happens, because there’s no local variable or parameter with that name, it automatically finds what it wants from the outer scope.
When it comes to actually writing to the value you need to use the special global
keyword to tell the interpreter that inside of this scope, all references to _myGlobal
actually mean the one from the outer scope. Without that, the assignment in MyCopyCommand.run()
would create a local variable with that value, which would immediately go out of scope.