Best Practice for Add-ons using Third-Party Packages

I am an add-on developer and recently I would like to use pygments to highlight code in Anki within my add-on. In principle I can copy the whole package folder together with my addon and use relative import to achieve this.

However unfortunately, the pygments package is designed to use absolute import within the package. For example, in pygments/filter/__init__.py, I found something like this:

from pygments.plugin import find_plugin_lexers

This would suggest that if I use relative import at the top level, I should also modify everywhere in the pygments package to use relative import instead of absolute import, which involves a great number of work and is not scalable.

Is there any better practice to use a “internally absolute import” third-party package?

this is not a real answer.

Just a note: glutanimate’s popular syntax highlighting add-on also uses the pygments package and uses sys.path.insert.

3 Likes

As an alternative solution, according to Python documentation, you can directly import a local source file using spec_from_file_location function.

Let’s say pygments folder is located in libs folder as follows:

+---addons21
|   +---your_addon_root
|   |   +---libs
|   |   |   +---pygments

you can import it as follows:

import sys
import pathlib
import importlib.util

addon_root = pathlib.Path(__file__).resolve().parent
pygments_source = addon_root / 'libs' / 'pygments' / '__init__.py'
spec = importlib.util.spec_from_file_location('pygments', pygments_source)
module = importlib.util.module_from_spec(spec)
sys.modules['pygments'] = module
spec.loader.exec_module(module)

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

code = 'print("Hello World")'
print(highlight(code, PythonLexer(), HtmlFormatter()))
4 Likes