Ways to organize Settings in Sublime Text plugin

Viewed 609

Perhaps it is another round of "static vs instance" but I am trying to be devil in details. Note that I am fairly new to Python and plugin development.

Some plugins use the following code:

s = sublime.load_settings(__name__ + '.sublime-settings')

class Settings:
  def load(self):
    self.setting1 = s.get('setting1', 'default1')
    self.setting2 = s.get('setting2', 'default2')
    ...

# Global Scope

settings = Settings()
settings.load()
s.add_on_change(__name__ + '-reload', settings.load)

There is nothing particularly wrong with this example except load_settings and add_on_change methods should belong to Settings:

class Settings:
  def __init__(self):
    self.settings = sublime.load_settings(__name__ + '.sublime-settings')
    self.settings.add_on_change(__name__ + '-reload', self.setup)
    self.setup()

  def setup():
    self.setting1 = self.settings.get('setting1', 'default1')
    self.setting2 = self.settings.get('setting2', 'default2')
    ...

# Global Scope

settings = Settings()

Now Settings class encapsulates all functionality. But do we really need instances of this class ? I don't think so. That's why static should be used:

class Settings:
  settings = sublime.load_settings(__name__ + '.sublime-settings')

  @staticmethod
  def init():
    Settings.settings.add_on_change(__name__ + '-reload', Settings.setup)
    Settings.setup()

  @staticmethod
  def setup():
    Settings.setting1 = Settings.settings.get('setting1', 'default1')
    Settings.setting2 = Settings.settings.get('setting2', 'default2')
    ...

# Global Scope

Settings.init()

The advantages (if any) of the example above are:

  • class encapsulates all functionality related to settings
  • no need to create instances to access settings

Are there any other "decent" ways to organize Settings ?

2 Answers

Your second example is the best approach, everything encapsulated in a class. The @staticmethod approach has no advantages that I can think of - there is nothing at all wrong with having a class which will only ever have one instance created at a time.

The global settings = Settings() assignment should be called from inside plugin_loaded() to ensure that the ST API is ready, otherwise sublime.load_settings(FILENAME) could fail.

Callbacks should be used so that if the user changes a setting Sublime Text does not need to be restarted for the setting's value to be updated. These should be removed in plugin_unloaded() in case the user uninstalls the plugin.

Here's a rough template taken from one of my plugins. It should serve as a good starting position from which settings handling can be added to Sublime Text plugins.

Code also in this GitHub Gist.

import sublime
import sublime_plugin

# The global scope ensures that the settings can
# be easily accessed from within all the classes.
global settings

def plugin_loaded():
    """ 
    This module level function is called on ST startup when the API is ready. 
    """

    global settings
    settings = Settings()
    settings.load_all()

def plugin_unloaded():
    """
    This module level function is called just before the plugin is unloaded.
    """

    settings.remove_callbacks()

class Settings:
    """
    Handles all the settings. A callback method is added for each setting, it 
    gets called by ST if that setting is changed in the settings file.
    """

    def __init__(self):

        FILENAME = "YourPluginName.sublime-settings"
        self.settings = sublime.load_settings(FILENAME)

        # User configurable settings.
        self.max_display_length = None
        self.monospace_font     = None
        self.ellipsis_symbols   = None
        self.prefix_custom      = None
        self.command_names      = None
        # ...

    def load_all(self):
        self.init_setting("max_display_length", self.set_max_display_length)
        self.init_setting("monospace_font", self.set_monospace_font)
        self.init_setting("ellipsis_symbols", self.set_ellipsis_symbols)
        self.init_setting("prefix_custom", self.set_prefix_custom)
        self.init_setting("command_names", self.set_command_names)
        # ...

    def init_setting(self, setting_name, setting_method):
        """
        Calls the setting_method to set the setting's value and registers the 
        setting_method as a callback so that it will be called by ST if the 
        setting's value is changed by the user.
        """

        setting_method()
        self.settings.add_on_change(setting_name, setting_method)

    def remove_callbacks(self):
        self.settings.clear_on_change("max_display_length")
        self.settings.clear_on_change("monospace_font")
        self.settings.clear_on_change("ellipsis_symbols")
        self.settings.clear_on_change("prefix_custom")
        self.settings.clear_on_change("command_names")
        # ...

    # Methods for the user configurable settings.

    def set_max_display_length(self):
        DEFAULT = 70
        MIN_LENGTH = 50
        value = self.integer_setting("max_display_length", DEFAULT, MIN_LENGTH)
        self.max_display_length = value

    def set_monospace_font(self):
        DEFAULT = True
        value = self.boolean_setting("monospace_font", DEFAULT)
        self.monospace_font = value

    def set_ellipsis_symbols(self):
        DEFAULT = "…"
        value = self.string_setting("ellipsis_symbols", DEFAULT)
        self.ellipsis_symbols = value

    def set_prefix_custom(self):
        DEFAULT = ""
        # This setting may be set to a string or a list of strings;
        # if it is a list then ensure all list elements are strings.
        value = self.list_or_string_setting("prefix_custom", DEFAULT)
        if isinstance(value, list):
            for index, item in enumerate(value):
                if not isinstance(item, str):
                    value[index] = str(item)
        self.prefix_custom = value

    def set_command_names(self):
        DEFAULT = []
        value = self.list_setting("command_names", DEFAULT)
        self.command_names = value

    # Methods for settings retrieval; all will return a
    # setting of the required type or the default value.

    def string_setting(self, setting, default):
        return self.setting_of_type(setting, default, str)

    def list_setting(self, setting, default):
        return self.setting_of_type(setting, default, list)

    def boolean_setting(self, setting, default):
        return self.setting_of_type(setting, default, bool)

    def list_or_string_setting(self, setting, default):
        return self.setting_of_type(setting, default, (str, list))

    def setting_of_type(self, setting, default, required_type):
        value = self.settings.get(setting, None)
        return value if isinstance(value, required_type) else default

    # Special case.

    def integer_setting(self, setting, default, min_value):
        value = self.settings.get(setting, None)
        return value if self.is_integer(value) and value >= min_value else default

    def is_integer(self, value):
        # Bool is a subclass of int; isinstance(False, int) == True.
        return isinstance(value, int) and not isinstance(value, bool)
Related