Search code examples
pythonsublimetext2sublimetext3sublimetextsublime-text-plugin

How to import classes from another directory in sublime plugin


I want to have a directory structure like:

myplugin
  -lib
    -myplugin.py
    -file.py
    -another.py
  -tests
    -file_tests.py
    -another_tests.py 

I can't make sublime recognize my plugin if it is in the child directory. That's fine, I can keep the entry point in the root directory and import my other classes; however, I can't make that work either. I've written the code and run my tests fine, like nosetest tests/ and everything passes - when sublime tries to load the package I get: ImportError: No module named 'lib'. I'm new to both sublime plugin development and Python, but basically, my plugin is like:

import sublime
import sublime_plugin
from lib.something import Something
from lib.something_else import SomethingElse
from lib.something_else_else import SomethingElseElse

class MyPluginCommand(sublime_plugin.TextCommand):

Solution

  • You're on the right track; Sublime only scans and automatically loads files a single directory deep inside the Packages folder as you've noticed.

    Your problem is that the module name that you want to import needs to be qualified with the name of the package that it's stored in. In terms of the code you gave above, the following would work, assuming that the plugin that the lib directory is stored in was named myplugin:

    import sublime
    import sublime_plugin
    from myplugin.lib.something import Something
    from myplugin.lib.something_else import SomethingElse
    from myplugin.lib.something_else_else import SomethingElseElse
    
    class MyPluginCommand(sublime_plugin.TextCommand):