Sublime Forum

Call methods in another package?

#1

Is it possible to call methods in another package from my own package?
I want to call another package’s methods from inside of my plugin.

I developed and maintain package called ‘MarkdownTOC’ which enables to create and add ‘Table of Contents’ in markdown documents.
Some user use my plugin with another plugin called ‘MarkdownPreview’. And they pointed out that there are differences between anchors of headings generated by my plugin and generated by MarkdownPreview. And links didn’t work because of these differences.

I think it’s ok if I write same implementation as MarkdownPreview’s. But I found something wrong with its implementation (I think It’s not perfect). And it’s not good for thinking about maintenance in the future.

So I’m wondering if I could call MarkdownPreview’s methods inside of my plugin. And I have to confirm that MarkdownPreview package existed in user’s installed packages or not at first.
Is it possible? or any idea?
Is there any examples about communication between two packages?

Thank you for reading :slightly_smiling:

1 Like

[Question] How install Package Control package as dependency?
#2

Yes, you can just import methods from other packages, but unfortunately not in your case, because the Markdown Preview package has a space inside its name. Otherwise you would write (This is no valid syntax with a space in the module/package name):

try:
    from MarkdownPreview.module_name import foo_bar
except ImportError:
    def foo_bar():
        pass
2 Likes

#3

If you are only targeting Sublime Text 3, you can do:

import sys

try:
    mymod = sys.modules["Package Name.mymod"]
except KeyError:
    print("module not found")

This will require the above code is run after the package being imported is loaded by Sublime Text. This may require lazy instantiation of mymod by initially setting it to None.

Note also that the imported module may be reloaded by Sublime Text if the package is upgraded or disabled and re-enabled.

4 Likes

#5

Thank you so much for your quick responses!! :heart_eyes:
Both of yours work fine, I think.
I’m going to write codes according to your suggestions.

0 Likes