Sublime Forum

Settings not loading fast enough

#1

I’m developing a plugin which allows me to create a file which is pre-saved so that I can execute it immediately. The file is deleted upon closure so it’s useful to quickly test code. However, I’m having problems loading and retrieving settings. I have the sublime.load_settings(...) which produces the correct <sublime.Settings object at ...>. My problem lies where I use settings.get(...) which seems to return None when I first start up Sublime. However, if I save the plugin file - it reloads the plugin and the retrieval of the settings works fine. It’s very odd and has only recently begun happening.

I can’t really give any test code to recreate the problem as I can’t tell if it’s a local problem or not. Any idea why trying to get the settings when the plugin loads doesn’t work. FYI, the call to settings.get happens in the global scope (not in a TextCommand class) and I assign the results to global variables instead of giving each class a self.settings attribute.

0 Likes

#2

Just from your problem description, it sounds like you’re trying to access the API before the plugin host has fully loaded. For example, this won’t work:

import sublime
import sublime_plugin


s = sublime.load_settings("Preferences.sublime-settings")
print("=>", s.get("font_size"))

When you start Sublime up, you see this in the console:

reloading plugin User.test
=> None
plugins loaded

However, saving the plugin causes it to work:

reloading plugin User.test
=> 12

The reason for that is with a few exceptions, the API is not available to plugin code immediately at application start time. Sublime loads the initial state from the saved session (if any) and then starts getting the package environment ready in the background. The full API is only available once the plugin host is ready to go .

So doing anything top level that talks to the API, such as the above, is a direct no-no. It won’t work when Sublime starts, but it works afterwards because by the time you manually save the file and trigger a reload, the plugin host is available.

You can use the plugin_loaded module endpoint to know when your plugin is fully loaded and the plugin host is ready to go, and put all of the top level code that needs to talk to the API in there. Of course anything that is invoked from the run method of a Command subclass is OK because in order for your command to be executed the plugin environment must already be ready.

An example of the above code done in a way that works even at startup is:

import sublime
import sublime_plugin

def plugin_loaded():
    s = sublime.load_settings("Preferences.sublime-settings")
    print("=>", s.get("font_size"))
1 Like